Home > other >  Add property and copy array of objects into an nested objects
Add property and copy array of objects into an nested objects

Time:06-08

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"}]

CodePudding user response:

Maybe function like this where getClasses function returns classes array.

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

CodePudding user response:

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"}]

  • Related