Home > Software design >  Copy objects from the nested array into the new array in React JS
Copy objects from the nested array into the new array in React JS

Time:07-12

I have a big nested array of objects and each object has an object called 'set. Something like this:

const arr1 = [
  {
    id: 1,
    subject: 'Subject',
    set: {
      title: 'Title',
      subTitle1: 'SubTitle',
      subTitle2: 'SubTitle',
    },
  },
  {
    id: 2,
    subject: 'Subject',
    set: {
      title: 'Title',
      subTitle1: 'SubTitle',
      subTitle2: 'SubTitle',
    },
  },
]

I want to get the content of each 'set' object from 'arr1' into the 'arr2', like this:

const arr2 = [
  {
    title: 'Title',
    subTitle1: 'SubTitle',
    subTitle2: 'SubTitle',
  },
  {
    title: 'Title',
    subTitle1: 'SubTitle',
    subTitle2: 'SubTitle',
  },
]

CodePudding user response:

You can use .map to extract the set from each object

const arr1 = [
  {
    id: 1,
    subject: 'Subject',
    set: {
      title: 'Title',
      subTitle1: 'SubTitle',
      subTitle2: 'SubTitle',
    },
  },
  {
    id: 2,
    subject: 'Subject',
    set: {
      title: 'Title',
      subTitle1: 'SubTitle',
      subTitle2: 'SubTitle',
    },
  },
]

const arr2 = arr1.map(a => a.set);

console.log(arr2 );

  • Related