开发者

How to loop through key/value object in Javascript? [duplicate]

开发者 https://www.devze.com 2023-01-01 18:16 出处:网络
This question already has answers here: For..In loops in JavaScript - key value pairs (19 answers) Closed 8 years ago.
This question already has answers here: For..In loops in JavaScript - key value pairs (19 answers) Closed 8 years ago.
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", ....


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];
        }
    }
}


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


Something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消