Home > other >  js how to use .reduce() to get an object with arrays out of a nested object with arrays
js how to use .reduce() to get an object with arrays out of a nested object with arrays

Time:01-13

I am looking for a solution on how to reduce the following object:

const myObject = {
  first: 'A',
  second: {
    nestedArr1: ['nestA', 'nestB'],
    nestedArr2: ['nestC', 'nestD'],
  }
}

to the expected result:

const myObject = {
      first: 'A',
      nestedArr1: ['nestA', 'nestB'],
      nestedArr2: ['nestC', 'nestD'],
    }

Thanks in advance!

disclaimer: I was looking for an answer and there are some, but just not using .reduce() (or at least I couldn't find anything.

CodePudding user response:

You don't need any function for that, just use spread operator:

const myObject = {
  first: 'A',
  second: {
    nestedArr1: ['nestA', 'nestB'],
    nestedArr2: ['nestC', 'nestD'],
  }
}

const {
  second,
  ...newObj
} = {
  ...myObject,
  ...myObject.second
}

console.log(newObj)

  • Related