如何使用JavaScript或jQuery更改数组内对象的值?

2022-08-29 23:39:36

下面的代码来自jQuery UI Autocomplete:

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 = ....


答案 1

这很简单

  • 使用方法查找对象的索引。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])

答案 2

您必须在数组中搜索,如下所示:

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”和 projects[“jquery-ui”] 表示法。