My data
var data={
key:value,
key:value,
key:value
};
Expected output
var data=[
{key:value},
{key:value},
{key:value}
];
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));
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;
})
)
var data = { key: value }, so please give us a verifiable code sample