Currently, I am working with an array of objects that has a nested structure like this:
props: {
dog: {
default: '',
type: String
},
cat: {
default: '',
type: String
},
bird: {
default: '',
type: String
}
},
{
dog: {
default: '',
type: String
},
bird: {
default: '',
type: String
},
fish: {
default: '',
type: String
}
}
I want to flatten the top level of this array of objects so that all nested objects are on the same level without duplicates. The desired structure is as follows:
{
dog: {
default: '',
type: String
},
bird: {
default: '',
type: String
},
fish: {
default: '',
type: String
}
}
Since I don't know in advance what keys will be present in the structure, I need to loop through it dynamically without specifying any key names. I have attempted to extract each individual nested object and store them into an array using the following code snippet:
const newArray = [];
for (let i = 0; i < objSize; i++) {
// checks if properties exist
if (JSON.stringify(petObj[i].options.props) !== '{}') {
newArray.push(petObj[i].options.props);
const numProps = Object.keys(newArray[i]).length;
for (let j = 0; j < numProps.length; j++) {
console.log(petObj[i].options.props[j]);
}
}
However, I am encountering issues such as null or undefined errors after adding the inner for loop. Can anyone suggest a potential solution?