qinHaiXiang qinHaiXiang - 5 months ago 33x
Javascript Question

How to change value of object which is inside an array using javascript or jquery?

these code come from 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,when I want to change the desc value of jquery-ui,how can I do than??

Thank you very much!!

Is there much faster way to get the data? I mean give the object a name to fetch its data.Just like the object inside array.So,can I used in that way : jquery-ui.jquery-ui.desc = ....


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


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