I have one array like below
[
{
"__typename": "ConfigurableProduct",
"uid": "MzY3",
"name": "AISLING BODYSUIT",
"crosssell_products": [
{
"__typename": "ConfigurableProduct",
"uid": "NTI=",
"name": "Product 1"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 2"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 3"
}
]
},
{
"__typename": "ConfigurableProduct",
"uid": "MzI4",
"name": "CERYS BODYSUIT",
"crosssell_products": [
{
"__typename": "ConfigurableProduct",
"name": "Product 4"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 5"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 6"
}
]
}
]
I want single array with data which is contain crosssell_products array it means I want below format
"crosssell_products": [
{
"__typename": "ConfigurableProduct",
"uid": "NTI=",
"name": "Product 1"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 2"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 3"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 4"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 5"
},
{
"__typename": "ConfigurableProduct",
"name": "Product 6"
},
]
I tried below code but not working
let aa = getRelatedData?.products?.items.reduce(function (a, b) {
return a.concat(b);
}, []);
4
Answers
You need to use
flatMap
.map
will return an array of arrays, hence the need to useflatMap
instead.You can also use your method of iterating and reducing:
But
flatMap
is much more concise and illustrate the intent better.You can use
flatMap()
Operator in javascript accomplish a flatten array.Try
Array.flatMap()
as belowThis will not fail, even if the
crosssell_products
not exist in the array or undefined.You can use the
map
to create a new array that contains only thecrosssell_products
arrays from each object in the original array. Then,concat
it to combine these arrays into a single array and assign combined array to thecrosssell_products
property of a new object.