提问者:小点点

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


下面的代码来自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=。。。。


共3个答案

匿名用户

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

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方法查找对象的索引。
  • 将索引存储在变量中。
  • 执行如下所示的简单更新:YourArray[indexThatyouFind]

null

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

匿名用户

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