Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript或jQuery更改数组内部对象的值?(How to change value of object which is inside an array using JavaScript or jQuery?)

The code below comes from jQuery UI Autocomplete:(下面的代码来自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"
    }
];

For example, I want to change the desc value of jquery-ui .(例如,我想更改jquery-uidesc值 。)

How can I do that?(我怎样才能做到这一点?)

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 = ....)   ask by qinHaiXiang translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is quite simple(很简单)

  • Find the index of the object using findIndex method.(使用findIndex方法查找对象的索引。)
  • Store the index in variable.(将索引存储在变量中。)
  • Do a simple update like this: yourArray[indexThatyouFind](做这样的简单更新: 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]) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...