Shaun
Shaun

Reputation: 471

How to render two different arrays data into a single array of objects?

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

Upvotes: 1

Views: 139

Answers (3)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

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);

Upvotes: 4

user11081925
user11081925

Reputation:

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

Upvotes: 0

zixiCat
zixiCat

Reputation: 1059

Use Array.prototype.flat()

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

Upvotes: 0

Related Questions