1

In my react state, I have data coming in into two different arrays and I would like my component to put both arrays data in a single array. This is the data format that I have for both arrays:

data: {
  array1: [
    {
      name: "John Doe"
    },
    {
      name: "Bob Williams"
    }
  ]

  array2: [
    {
      name: "Clark Kent"
    },
    {
      name: "Bruce Wayne"
    }
  ]
}

How can I make my code return data so the end result looks like the defined below:

_.map(Object.values(this.state.data), (item,key) => {
  return _.map(item, (data) => {
    return {
      name: data.name
    }
  })
})

Desired output:

data: [
  { name: "John Doe" },
  { name: "Bob Williams" },
  { name: "Clark Kent" },
  { name: "Bruce Wayne" }
]

3 Answers 3

4

You can use Spread operator ... to merge 2 arrays into one.

const data = {array1:[{name:"John Doe"},{name:"Bob Williams"}],array2:[{name:"Clark Kent"},{name:"Bruce Wayne"}]};;

const result = {data: [...data.array1, ...data.array2]};
console.log(result);

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

2 Comments

Thanks Nguyen for the response. This looks good. Will this also work if I have other properties inside both arrays and if I want to target the other properties to display the data on the page?
Yes, it is @Shaun
0

Use Array.prototype.flat()

const data = Object.values(this.state.data).flat();

Comments

0
Object.values(this.state.data).reduce((p, c) => p.concat(c), []);

Comments

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.