简体   繁体   中英

Add property and copy array of objects into an nested objects

I would like to copy an array of objects in a nested object with new property. How can I use es6 to achieve something like this

I would like to copy:

['cat', 'Dog', 'monkey'] into

[{"text":"cat"},{"text":"Dog","extraClasses":["ti-extra"]}, {"text":"monkey"}]

Use Array#map , and you can test for the items that should be different so the extra props can be added to them.

 const input = ['cat', 'Dog', 'monkey'], output = input.map( text => text === "Dog" ? ({text, "extraClasses":["ti-extra"]}) : ({text}) ); console.log( output ); //[{"text":"cat"},{"text":"Dog","extraClasses":["ti-extra"]}, {"text":"monkey"}]

Maybe function like this where getClasses function returns classes array.

['cat', 'Dog', 'monkey'].map((item) => {
  return { text: item, extraClasses: getClasses() };
});

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