I would like to know how to flatten the array of objects without flap map in javascript
If the of object of arrays object has length greater than 1, flatten
in my example property black has more than object so return that in array of objects
var obj ={
"details": {
"black": [
{
value: 100,
name: "xxx"
},
{
value: 200,
name: "yyy"
}
]
},
"sales": {
"blue": [
{
value: 50,
name: "abc"
}
],
"ALL": [
{
value: 20,
name: "100"
}
]
}
}
Expected Output
[
{
value: 100,
name: "xxx"
},
{
value: 200,
name: "yyy"
}
]
have tried
const result = Object
.values(obj)
.flatMap(v =>
Object.values(v as any)
.filter((group: any) => group.length > 1)
)
without flapmap how to do using javascript
You can create a recursive flatten function using Array.reduce() that takes a multidimensional array, and converts it to a flat array (TS playground):
const obj = {"details":{"black":[{"value":100,"name":"xxx"},{"value":200,"name":"yyy"}]},"sales":{"blue":[{"value":50,"name":"abc"}],"ALL":[{"value":20,"name":"100"}]}}
const flatten = arr =>
arr.reduce((acc, a) => acc.concat(
Array.isArray(a) ? flatten(a) : a
), [])
const result = flatten(Object.values(obj)
.map(v =>
Object.values(v)
.filter(group => group.length > 1)
)
)
console.log(result)
Note: you can also use Array.flat() but since it came out with Array.flatMap() you would probably still have a compatibility problem.
var obj ={
"details": {
"black": [
{
value: 100,
name: "xxx"
},
{
value: 200,
name: "yyy"
}
]
},
"sales": {
"blue": [
{
value: 50,
name: "abc"
}
],
"ALL": [
{
value: 20,
name: "100"
}
]
}
}
console.log(obj.details.black)