Is there a way to flatten any array values within an object in JavaScript, not limited to just ecommerce? For example:
var sample = {
price: "999",
description: "...",
ecommerce: {
products: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
}
};
I want the output to be:
{
price: "999",
description: "..."
ecommerce: {
products_1: {
brand: "apple",
category: "phone"
},
products_2: {
brand: "google",
category: "services"
}
}
}
What is the most efficient way to achieve this using JavaScript (ES6/7)?
Thank you!
Note: I've tried a solution but it's not working as expected. Is there a better functional approach to this?
function flattenArray(array) {
var obj = array.reduce((acc, cur, i) => {
acc[i] = cur;
return acc;
}, {});
return obj;
}
function cleanObject(object) {
for (let key in object) {
let testObject = object[key];
if (Array.isArray(testObject)) {
testObject = flattenArray(testObject)
} else if (typeof(testObject) === 'object') {
testObject = cleanObject(testObject);
}
return testObject;
}
return object;
}
var clean = cleanObject(sample);
UPDATE: What if the object is structured like this:
var sample = {
price: "999",
description: "...",
differentArray: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
};
This time the array is under a different key and nested at a different level.