ALI
ALI

Reputation: 23

Javascript Get flat array from object contain multiple arrays

I'm trying to merge multiple arrays from one object using JavaScript(React-Native), the example of the object is :

{"10419": ["37046", "37047"], "9138": ["32809"]}

The result should be like so:

["37046","37047","32809"]

I need to ignore the object name and end up with only one flat array

I used flat() function but it seems not working as I need.

my try looks like :

    var obj = this.state.obj // will contain the object
    console.log(obj.flat()) // I know that work only with arrays but I tried it out 

Thanks

Upvotes: 2

Views: 427

Answers (2)

Iyashi
Iyashi

Reputation: 572

Object.values(this.state.obj).flat()

Upvotes: 2

Derek Wang
Derek Wang

Reputation: 10193

  • Using Object.values, you can get the values inside the object. That will be 2d array from your input.
  • Using Array.prototype.flat, you can make it as 1d array as follows.

const input = {"10419": ["37046", "37047"], "9138": ["32809"]}
const result = Object.values(input).flat();
console.log(result);

Upvotes: 3

Related Questions