javascript - add key value pair of objects in an array -
function person (name, age) { this.name = name; this.age = age; } var family = [] var people = {alice:40, bob:42, michelle:8, timmy:6}; (var key in people) { family.push({key:people[key]}) } console.log(family);
this not giving me keys. giving 'key' each key. proper way add {key:value} pair of objects in array?
update based on k3n solution below, understood works best if declaring constructor each time:
keys = object.keys(people); (var = 0; < keys.length; i++) { family.push(new person(keys[i], people[keys[i]])); }
since people arrays contains name of person key, , value being age (be careful if 2 persons same name nuclear reaction in time-space happens...!).
you can this:
function person (name, age) { this.name = name; this.age = age; } var family = [] var people = {alice:40, bob:42, michelle:8, timmy:6}; var keys = object.keys(people); // list (ownproperty) keys in object for(var = 0, key; key = keys[i]; i++) { // loop through family.push(new person(key, people[key])); // push } document.write(json.stringify(family)); // demo output
Comments
Post a Comment