How to encode key / value object in javascript

var user = {};

Now I want to create a setUsers method that takes an object of a key / value pair and initializes the user variable.

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

where data:

 234: "john", 23421: "smith", .... 
+81
javascript
Jun 02 '10 at
source share
3 answers

Beware of properties inherited from the prototype of the object (this can happen if you include any libraries on your page, for example, older versions of Prototype). You can verify this using the hasOwnProperty() object method. This is usually 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]; } } } 
+136
Jun 02 '10 at 15:07
source share
 for (var key in data) { alert("User " + data[key] + " is #" + key); // "User john is #234" } 
+53
Jun 02 2018-10-02T00:
source share

Something like that:

 setUsers = function (data) { for (k in data) { user[k] = data[k]; } } 
+9
Jun 02 '10 at 2:53 a.m.
source share



All Articles