Skip to content
Advertisement

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

The code below comes 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, I want to change the desc value of jquery-ui. 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 = ....

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement