3

My data

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

Expected output

var data=[
 {key:value},
 {key:value},
 {key:value}
];
CroMagnon
1,2027 gold badges21 silver badges32 bronze badges
asked Feb 10, 2017 at 7:25
1
  • i doubt that this is your data, if you declare it like this, your data is actually var data = { key: value }, so please give us a verifiable code sample Commented Feb 10, 2017 at 7:27

5 Answers 5

3

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

answered Feb 10, 2017 at 7:36
Sign up to request clarification or add additional context in comments.

Comments

2

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)

answered Feb 10, 2017 at 7:36

Comments

2

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

answered Feb 10, 2017 at 7:28

Comments

0

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;}
answered Feb 10, 2017 at 7:38

Comments

0

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 
answered Feb 10, 2017 at 7:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.