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);
}, []);
You can use flatMap()
Operator in javascript accomplish a flatten array.
Refer official documentation here.
var arr = [
{
"__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"
}
]
}
];
const results = arr.flatMap(v => v.crosssell_products);
console.log(results)