以下代码来自 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 = ....
最佳答案
很简单
- 使用
findIndex
方法查找对象的索引。 - 将索引存储在变量中。
- 像这样做一个简单的更新:
yourArray[indexThatyouFind]
//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])
关于javascript - 如何使用 JavaScript 或 jQuery 更改数组内对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4689856/