Javascript Get flat array from object contain multiple arrays

Viewed 106

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

2 Answers
  • 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);

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