以下代码来自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 = ....
的东西
发布于 2011-01-14 18:05:49
您必须在数组中进行搜索,如下所示:
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“符号。)
发布于 2017-01-30 22:43:43
这很简单
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])
发布于 2018-08-07 10:59:42
多亏了ES6,这是最好的解决方案。
这将返回一个新的数组,其中包含一个等于"jquery-ui“的值,并替换了该对象的描述。
const newProjects = projects.map(p =>
p.value === 'jquery-ui'
? { ...p, desc: 'new description' }
: p
);
https://stackoverflow.com/questions/4689856
复制相似问题