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; }) )
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)
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
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;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.