Zee
Zee

Reputation: 8488

Separate keys and values from object

I have an object like :

var obj1 = [{ first : 1, second : 2 },
            {third : 3, fourth : 4},
            {fifth : 5, sixth : 6}]; 

I want to separate the keys and values into 2 different arrays such that the result should be

var labels = [first, second, third, fourth, fifth, sixth];
var values = [1,2,3,4,5,6]; 

I tried this :

var labels = [];
var values = [];
for(var key in obj1[0]){
    labels.push(key);
    values.push(obj1[0][key]);
}

But it results in

labels = ["first","second"];
values = [1,2];

I know this happens because I am iterating only the 0 index position. Can anyone suggest me a way to achieve the expected output.

Upvotes: 1

Views: 4330

Answers (2)

Samurai
Samurai

Reputation: 3729

for (var i = 0; i < obj1.length; i++) {
    for (var key in obj1[i]) {
        labels.push(key);
        values.push(obj1[i][key]);
    }
}

Upvotes: 2

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

var obj1 = [{ first : 1, second : 2 },
            {third : 3, fourth : 4},
            {fifth : 5, sixth : 6}]; 

var key=[];
var value=[];
obj1.forEach(function(item){
 
  for(i in item)
  {
    key.push(i);
    value.push(item[i]);
  }
   
});

console.log(key);
console.log(value);

Upvotes: 4

Related Questions