user2290820
user2290820

Reputation: 2759

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


for (var key in people) {
  family.push({key:people[key]})
}

console.log(family);

This is not giving me the keys. its giving 'key' for each key. what is the proper way to add {key:value} pair of objects in an array?

UPDATE Based on K3N solution below, this is what i understood works best if we are declaring from a constructor each time:

keys = Object.keys(people);
for (var i = 0; i < keys.length; i++) {
  family.push(new Person(keys[i], people[keys[i]]));
}

Upvotes: 0

Views: 80

Answers (2)

bugwheels94
bugwheels94

Reputation: 31950

Wither use Bracket notation so that key can be treated as a variable property name

for (var key in people) {
    var temp={};
    temp[key]=people[key]
    family.push(temp)
}

Or Computed property name

for (var key in people) {
  family.push({[key]:people[key]})
}

Upvotes: 2

user1693593
user1693593

Reputation:

Since your people arrays contains name of the person as key, and value being the age (be careful as if you get two persons with the same name nuclear reaction in time-space happens...!).

You can do it like 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 all (ownProperty) keys in object
for(var i = 0, key; key = keys[i]; i++) {     // loop through
  family.push(new Person(key, people[key]));  // push it
}

document.write(JSON.stringify(family));       // demo output

Upvotes: 3

Related Questions