I'm trying to write a function that will accept a nested object array, and dynamically return the flattened result. arrayProperties.filter()
is not returning an array of objects like I expect.
const data = [
{
parKeyA: "parValA",
parKeyA1:
{chiKeyA1: "chiValA1", chiKeyA2: "chiValA2"},
parKeyA2: {chiKeyA3: "chiValA3"}
},
{
parKeyB: "parValB",
parKeyB1:
{chiKeyB1:"chiValB1"}
}
]
flatData = flatNestedObjArray(data);
console.log(flatData);
function flatNestedObjArray(array) {
let flatArray = array.map(element => {
let arrayProperties = Object.entries(element);
//filter not returning array of objects
let nestedObjects = arrayProperties.filter(property => {
const parentValue = property[1];
if (typeof parentValue === "object" && parentValue !== null) {
return parentValue;
}
});
//nestedObjects should be array of objects
let merged = nestedObjects.map(obj => element.concat(obj));
return merged;
});
return flatArray;
}
Expected Result:
const data = [
{
parKeyA: "parValA",
chiKeyA1: "chiValA1",
chiKeyA2: "chiValA2",
chiKeyA2: "chiValA2"
},
{
parKeyB: "parValB",
chiKeyB1:"chiValB1"
}
]
[1, 2, 3]
flattens to1, 2, 3
. Also, an object with duplicate keys is invalid. Ex.chiKeyA2
appears twice in the first object.