kishore
kishore

Reputation: 93

How to convert objects to Array of objects

My data

var data={
    key:value,
    key:value,
    key:value
};

Expected output

var data=[
    {key:value},
    {key:value},
    {key:value}
];

Upvotes: 3

Views: 85

Answers (5)

Andrew Willems
Andrew Willems

Reputation: 12448

You can use several ES6 shorthands to produce the desired output in one expression:

Object.keys(data).map(key => ({[key]: data[key]}))

The following code snippet demonstrates this:

const data = {
  key0:'value0',
  key1:'value1',
  key2:'value2'
};

const output = Object.keys(data).map(key => ({[key]: data[key]}));

console.log(JSON.stringify(output));

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use Object.keys and Array#map methods.

var data = {
  key: 'value',
  key1: 'value',
  key2: 'value'
};

console.log(
  // get all object property names(keys)
  Object.keys(data)
  // iterate over the keys array
  .map(function(k) {
    // generate the obect and return
    var o = {};
    o[k] = data[k];
    return o;
  })
)

Upvotes: 2

L. Vadim
L. Vadim

Reputation: 549

You can use Object.keys to have the keys:

Object.keys(data)
console.log(Object.keys(data)[0]) // will print first key 

Or you can use Object.values to get the values:

Object.values(data)
console.log(Object.values(data)[0]) // will print first key value 

Upvotes: 0

eldix_
eldix_

Reputation: 127

Try to do it this way:-

function json2array(json){
var output = [];
var keys = Object.keys(json);
keys.forEach(function(key){
    output.push(json[key]);
});
return output;}

Upvotes: 0

Sing
Sing

Reputation: 4052

Simple for in loop is a way to handle this :

var data = {
    key:  'value',
    key1: 'value1',
    key2: 'value2'
};
var arr = []; 
for(var k in data){
    var o = {}; 
    o[k]=data[k]; 
    arr.push(o)
}
console.log(arr)

Upvotes: 2

Related Questions