下面的代码来自jQuery UI自动完成:
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
例如,我想更改jquery-ui的desc值。我该怎么做呢?
此外,是否有更快的方法来获取数据?我的意思是给对象一个名字来获取它的数据,就像数组中的对象一样?比如jquery-ui。jquery-ui。desc = ....
你必须像这样在数组中搜索:
function changeDesc( value, desc ) {
for (var i in projects) {
if (projects[i].value == value) {
projects[i].desc = desc;
break; //Stop this loop, we found it!
}
}
}
然后像这样使用它
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
更新:
为了更快:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(根据Frédéric的评论,你不应该在对象键中使用连字符,或者你应该使用“jquery-ui”和项目["jquery-ui"]符号。)
这很简单
使用findIndex方法查找对象的索引。
将索引存储在变量中。
做一个简单的更新,像这样:
//Initailize array of objects.
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
//Find index of specific object using findIndex method.
objIndex = myArray.findIndex((obj => obj.id == 1));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
myArray[objIndex].name = "Laila"
//Log object to console again.
console.log("After update: ", myArray[objIndex])
这是我对这个问题的回应。我的下划线版本是1.7,因此我不能使用. findindex。
所以我手动获取了item的索引并替换了它。这里是相同的代码。
var students = [
{id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" },
{id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" },
{id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" },
{id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" }
]
下面的方法将用对象中更多的属性替换id:4的学生
function updateStudent(id) {
var indexOfRequiredStudent = -1;
_.each(students,function(student,index) {
if(student.id === id) {
indexOfRequiredStudent = index; return;
}});
students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"});
}
使用下划线1.8,它将被简化,因为我们有方法_.findIndexOf。
你可以在你的例子中使用。find so
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let project = projects.find((p) => {
return p.value === 'jquery-ui';
});
project.desc = 'your value'
// using higher-order functions to avoiding mutation
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// using higher-order functions to avoiding mutation
index = projects.findIndex(x => x.value === 'jquery-ui');
[... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)];
首先查找索引:
function getIndex(array, key, value) {
var found = false;
var i = 0;
while (i<array.length && !found) {
if (array[i][key]==value) {
found = true;
return i;
}
i++;
}
}
然后:
console.log(getIndex($scope.rides, "_id", id));
然后对这个索引做你想做的事情,比如:
美元(returnedindex)范围。someKey = "someValue";
注意:请不要使用for,因为for将检查所有的数组文档,使用while带有一个停止器,因此一旦找到它就会停止,从而更快地编写代码。
ES6方式,不改变原始数据。
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
//find the index of object from array that you want to update
const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');
// Make sure to avoid incorrect replacement
// When specific item is not found
if (objIndex === -1) {
return;
}
// make new object of updated object.
const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};
// make final new array of objects by combining updated object.
const updatedProjects = [
...projects.slice(0, objIndex),
updatedObj,
...projects.slice(objIndex + 1),
];
console.log("original data=", projects);
console.log("updated data=", updatedProjects);
使用map是最好的解决方案,不需要使用额外的库。(使用ES6)
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
根据以下数据,我们想用西瓜替换summerFruits列表中的浆果。
const summerFruits = [
{id:1,name:'apple'},
{id:2, name:'orange'},
{id:3, name: 'berries'}];
const fruit = {id:3, name: 'watermelon'};
有两种方法。
第一种方法:
//create a copy of summer fruits.
const summerFruitsCopy = [...summerFruits];
//find index of item to be replaced
const targetIndex = summerFruits.findIndex(f=>f.id===3);
//replace the object with a new one.
summerFruitsCopy[targetIndex] = fruit;
第二种方法:使用map和spread:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
summerFruitsCopy列表现在将返回一个更新对象的数组。
这是另一个涉及到发现的答案。
这取决于以下事实:
遍历数组中的每个对象,直到找到匹配的对象
每个对象都提供给你并且是可修改的
下面是关键的Javascript代码片段:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
下面是相同Javascript的另一个版本:
projects.find( function (p) {
if (p.value === 'jquery-ui') {
p.desc = 'your value';
return true;
}
return false;
} );
这里有一个更短的(有点邪恶的版本):
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
以下是完整的工作版本:
let projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
console.log( JSON.stringify( projects, undefined, 2 ) );
尝试使用forEach(item,index) helper
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let search_to_change = 'jquery'
projects.forEach((item,index)=>{
if(item.value == search_to_change )
projects[index].desc = 'your description '
})
这里有一个简洁明了的答案。我不是百分百确定这能行,但看起来还行。请让我知道,如果一个库是必需的,但我不认为是。另外,如果这在x浏览器中不起作用,请告诉我。我在Chrome IE11和Edge上尝试了这个功能,它们似乎都能正常工作。
var Students = [
{ ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
{ ID: 2, FName: "Jack", LName: "Test2", Age: 21},
{ ID: 3, FName: "John", LName: "Test3", age: 22},
{ ID: 4, FName: "Steve", LName: "Test4", Age: 22}
]
Students.forEach(function (Student) {
if (Student.LName == 'Test1') {
Student.LName = 'Smith'
}
if (Student.LName == 'Test2') {
Student.LName = 'Black'
}
});
Students.forEach(function (Student) {
document.write(Student.FName + " " + Student.LName + "<BR>");
});
输出应该如下所示
Ajay史密斯
杰克·布莱克
约翰Test3
史蒂夫Test4
javascript解构的力量
const projects = [
{
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
anotherObj: {
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
},
},
{
value: 'jquery-ui',
label: 'jQuery UI',
desc: 'the official user interface library for jQuery',
icon: 'jqueryui_32x32.png',
},
{
value: 'sizzlejs',
label: 'Sizzle JS',
desc: 'a pure-JavaScript CSS selector engine',
icon: 'sizzlejs_32x32.png',
},
];
function createNewDate(date) {
const newDate = [];
date.map((obj, index) => {
if (index === 0) {
newDate.push({
...obj,
value: 'Jquery??',
label: 'Jquery is not that good',
anotherObj: {
...obj.anotherObj,
value: 'Javascript',
label: 'Javascript',
desc: 'Write more!!! do more!! with JavaScript',
icon: 'javascript_4kx4k.4kimage',
},
});
} else {
newDate.push({
...obj,
});
}
});
return newDate;
}
console.log(createNewDate(projects));
假设您希望在修改期间运行更复杂的代码,您可能会使用if-else语句而不是三元操作符方法
// original 'projects' array;
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// modify original 'projects' array, and save modified array into 'projects' variable
projects = projects.map(project => {
// When there's an object where key 'value' has value 'jquery-ui'
if (project.value == 'jquery-ui') {
// do stuff and set a new value for where object's key is 'value'
project.value = 'updated value';
// do more stuff and also set a new value for where the object's key is 'label', etc.
project.label = 'updated label';
// now return modified object
return project;
} else {
// just return object as is
return project;
}
});
// log modified 'projects' array
console.log(projects);
let users = [
{id: 1, name: 'Benedict'},
{id: 2, name: 'Myles'},
{id: 3, name: 'Happy'},
]
users.map((user, index) => {
if(user.id === 1){
users[index] = {id: 1, name: 'Baba Benny'};
}
return user
})
console.log(users)
这段代码所做的是映射对象,然后匹配所需的
使用if语句,
if(user.id === 1)
一旦有匹配的地方使用它的索引交换
users[index] = {id: 1, name: 'Baba Benny'};
对象,然后返回修改后的数组
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
最简单的方法就是这样做
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
projects.find(data => data.value === "jquery").label ="xxxx"
console.log("------------>",projects)