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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4689856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:38:38  来源:igfitidea点击:

How to change value of object which is inside an array using JavaScript or jQuery?

javascriptjqueryarrays

提问by qinHaiXiang

The code below comes from jQuery UI Autocomplete:

下面的代码来自 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"
    }
];

For example, I want to change the desc value of jquery-ui. How can I do that?

例如,我想更改jquery-uidesc 值。我怎样才能做到这一点?

Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....

另外,有没有更快的方法来获取数据?我的意思是给对象一个名字来获取它的数据,就像数组中的对象一样?所以它会是这样的jquery-ui.jquery-ui.desc = ....

采纳答案by Aston

You have to search in the array like:

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

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!
     }
   }
}

and use it like

并像使用它一样

var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );

UPDATE:

更新:

To get it faster:

要更快地获得它:

var projects = {
   jqueryUi : {
      value:  'lol1',
      desc:   'lol2'
   }
};

projects.jqueryUi.desc = 'new string';

(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)

(根据 Frédéric 的评论,您不应该在对象键中使用连字符,或者您应该使用“jquery-ui”和 projects[“jquery-ui”] 符号。)

回答by Umair Ahmed

It is quite simple

这很简单

  • Find the index of the object using findIndexmethod.
  • Store the index in variable.
  • Do a simple update like this: yourArray[indexThatyouFind]
  • 使用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])

回答by Bimal Grg

ES6way, without mutatingoriginal data.

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

回答by kintaro

The best solution, thanks to ES6.

最好的解决方案,感谢 ES6。

This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".

这将返回一个新数组,其中包含一个等于“jquery-ui”的值的对象的替换描述。

const newProjects = projects.map(p =>
  p.value === 'jquery-ui'
    ? { ...p, desc: 'new description' }
    : p
);

回答by Frédéric Hamidi

You can use $.each()to iterate over the array and locate the object you're interested in:

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

$.each(projects, function() {
    if (this.value == "jquery-ui") {
        this.desc = "Your new description";
    }
});

回答by Ankit Kumar Rajpoot

Using map is the best solution without using extra libraries.(using ES6)

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

回答by user2765479

It's easily can be accomplished with underscore/lodash library:

可以使用下划线/lodash 库轻松完成:

  _.chain(projects)
   .find({value:"jquery-ui"})
   .merge({desc: "new desc"});

Docs:
https://lodash.com/docs#find
https://lodash.com/docs#merge

文档:
https: //lodash.com/docs#find
https://lodash.com/docs#merge

回答by abe kur

you can use .find so in your example

你可以在你的例子中使用 .find so

   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"
            }
        ];

let project = projects.find((p) => {
    return p.value === 'jquery-ui';
});

project.desc = 'your value'

回答by elasticrash

you need to know the index of the object you are changing. then its pretty simple

您需要知道要更改的对象的索引。那么它很简单

projects[1].desc= "new string";

回答by tsadkan yitbarek

I think this way is better

我认为这种方式更好

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