下面的代码来自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方法查找对象的索引。 将索引存储在变量中。 做一个简单的更新,像这样:

//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])

其他回答

用每个循环使用的条件更改值

projects.forEach((p,index)=>{
    if(index === 1){
       p.value = "Updated jquery-ui"
    }
})

使用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
);

我认为这样比较好

const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";

你可以使用$.each()遍历数组并定位你感兴趣的对象:

$.each(projects, function() {
    if (this.value == "jquery-ui") {
        this.desc = "Your new 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