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
5 Answers 5
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
Andrew Willems
12.6k10 gold badges57 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Sing
4,0623 gold badges32 silver badges42 bronze badges
Comments
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
Pranav C Balan
115k25 gold badges173 silver badges195 bronze badges
Comments
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;}
Comments
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
Comments
lang-js
var data = { key: value }, so please give us a verifiable code sample