161
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", ....
iammilind
  • 68,093
  • 33
  • 169
  • 336
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 12
    How an older question can be duplicated from a newer one? – Paulo Coghi Nov 18 '16 at 00:10
  • 3
    @PauloCoghi The mods were apparently drunk, nevermind... – Fusseldieb Aug 29 '18 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. – Inigo Feb 05 '19 at 04:15
  • The data model is objects of a object list `{{},..}`. When would I use this one instead of an array of objects `[{},..]` ? ok, [here](https://stackoverflow.com/a/31470302/1705829) is the answer, welcome to SO;). – Timo May 26 '22 at 19:04

3 Answers3

221

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];
        }
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 3
    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 Mar 28 '13 at 16:31
  • 2
    @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()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys). If you need to support IE <= 8, for example, you're stuck with `for...in`. – Tim Down Mar 28 '13 at 22:44
103
for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}
Felix
  • 88,392
  • 43
  • 149
  • 167
16

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}
Bialecki
  • 30,061
  • 36
  • 87
  • 109