163
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", ....
4
  • 12
    How an older question can be duplicated from a newer one? Commented Nov 18, 2016 at 0:10
  • 3
    @PauloCoghi The mods were apparently drunk, nevermind... Commented Aug 29, 2018 at 17:41
  • 2
    They chose the one with more votes. It's also written a little better. And it's got more answers with more votes. Makes sense to keep that one over this one. Commented Feb 5, 2019 at 4:15
  • The data model is objects of a object list {{},..}. When would I use this one instead of an array of objects [{},..] ? ok, here is the answer, welcome to SO;). Commented May 26, 2022 at 19:04

3 Answers 3

222

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];
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there anyway to do this without a for in loop? I'm worried about speed through large key value pairs (and I know that Crockford isn't a fan from using JSLint, but I'm not sure of his reasoning). Is there a reason to worry about these things?
@streetlight: It depends on the environment. If you can rely on having ECMAScript 5 (all modern browsers do, as does Node.js), you have options such as Object.keys(). If you need to support IE <= 8, for example, you're stuck with for...in.
106
for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Comments

17

Something like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.