简体   繁体   中英

Convert array of JSON object strings to array of JS objects in javascript

I have some data and I've converted it to an array of objects like:

[{"name": "aa", "birth":"19990101"},
{"name": "bb", "birth":"19990102"},
{"name": "cc", "birth":"19990103"}];

I want to convert this to an object like this:

{"aa":"19990101","bb":"19990102","cc":"19990103"};

What would be the best way to do this? Thanks!

You could use some destruction and assign the value to the given key.

 var array = [{ name: "aa", birth: "19990101" }, { name: "bb", birth: "19990102" }, { name: "cc", birth: "19990103" }], object = array.reduce((r, { name, birth }) => (r[name] = birth, r), {}); console.log(object); 

Object.assign with spread syntax ...

 var array = [{ name: "aa", birth: "19990101" }, { name: "bb", birth: "19990102" }, { name: "cc", birth: "19990103" }], object = Object.assign({}, ...array.map(({ name, birth }) => ({ [name]: birth }))); console.log(object); 

You can do it simply with reduce ,

var x = [{"name": "aa", "birth":"19990101"},
{"name": "bb", "birth":"19990102"},
{"name": "cc", "birth":"19990103"}];

var result = x.reduce((a, b) => (a[b['name']] = b['birth'], a), {});

Try this

 var a = [{"name": "aa", "birth":"19990101"}, {"name": "bb", "birth":"19990102"}, {"name": "cc", "birth":"19990103"}]; var map = {}; a.forEach( function(item){ map[item.name] = item.birth; }) console.log(map); 

Another way could be:

 var values =[ {"name": "aa", "birth":"19990101"}, {"name": "bb", "birth":"19990102"}, {"name": "cc", "birth":"19990103"} ]; var result = []; for(var i = 0; i < values.length; i++){ var item = {}; item[values[i].name] = values[i].birth; result.push(item); } console.log(result); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM