简体   繁体   中英

update value of each item in associative array

I have a JavaScript associative array, say:

var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";

How can I update value of each item in this array, so that output should be,

myArray["id1"] = "newValue";
myArray["id2"] = "newValue";
myArray["id3"] = "newValue";

Get all property name array using Object.keys() and then iterate over them update property value using Array#forEach method.

 var myArray = new Object(); myArray["id1"] = "completed"; myArray["id2"] = "notCompleted"; myArray["id3"] = "started"; Object.keys(myArray).forEach(function(k) { myArray[k] = 'newVal'; }); console.log(myArray); 


Faster way using a while loop.

 var myArray = new Object(); myArray["id1"] = "completed"; myArray["id2"] = "notCompleted"; myArray["id3"] = "started"; var names = Object.keys(myArray), i = names.length; while (i--) { myArray[names[i]] = 'newVal'; }; console.log(myArray); 

  • Use for in loop
  • Its always advisable to use hasOwnProperty to iterate across only the non-inherited properties.

 var myArray = new Object(); myArray["id1"] = "completed"; myArray["id2"] = "notCompleted"; myArray["id3"] = "started"; for (var prop in myArray) { if (myArray.hasOwnProperty(prop)) { myArray[prop] = 'newValue'; } } console.log(myArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM