0

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.

5
  • Since you defined it with const, do you want to mutate the object? Commented Jan 13, 2023 at 10:49
  • I would rather get a new object. Commented Jan 13, 2023 at 10:51
  • Well, then const (as you have it in your question) is not going to work... Commented Jan 13, 2023 at 10:52
  • if I would do it like: const parsed = results.reduce((acc, cur) => { return ... }, {}) then I think, that it should work Commented Jan 13, 2023 at 10:55
  • Yes, because you start with results (which must be an array?) and create parsed, but in your question you present it as if you start with myObject and want to end with myObject having a different structure. Commented Jan 13, 2023 at 10:58

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

ahh ofc, thanks. Why am I making things so overcomplicated?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.