How to loop through key/value object in Javascript?

JavascriptLoopsFor LoopIterationKey Value

Javascript Problem Overview


var user = {};

now I want to create a setUsers() method that takes a key/value pair object and initializes the user variable.

setUsers = function(data) {     
   // loop and init user    
}

where data is like:

234: "john", 23421: "smith", ....

Javascript Solutions


Solution 1 - Javascript

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

Solution 2 - Javascript

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Solution 3 - Javascript

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlankmanView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - JavascriptFelixView Answer on Stackoverflow
Solution 3 - JavascriptBialeckiView Answer on Stackoverflow