When working with an array of objects, I need to filter and extract all the keys. One challenge I face is when there are nested objects, I want to concatenate the key names to represent the nested structure. For example:
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]
I have been able to accomplish the above code, but when there are multiple nested objects within the data, I find myself adding more if conditions in my logic. I'm seeking a better way to handle this, so that regardless of the number of nested objects, the concatenation happens seamlessly.
The code snippet I used for the above scenario:
const itemsArray = [
{ id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
{ id: 2, item: "Item 002", obj: { name: 'Nilton002', message: "Free002", obj2: { test: "test002" } } },
{ id: 3, item: "Item 003", obj: { name: 'Nilton003', message: "Free003", obj2: { test: "test003" } } },
];
const csvData = [
Object.keys(itemsArray[0]),
...itemsArray.map(item => Object.values(item))
].map(e => e.join(",")).join("\n")
// Separating keys
let keys = []
const allKeys = Object.entries(itemsArray[0]);
for (const data of allKeys) {
if (typeof data[1] === "object") {
const gettingObjKeys = Object.keys(data[1]);
const concatingKeys = gettingObjKeys.map((key) => data[0] + "." + key);
keys.push(concatingKeys);
} else {
keys.push(data[0])
}
}
//Flating
const flattingKeys = keys.reduce((acc, val: any) => acc.concat(val), []);
My goal is to extract all the keys from the first object in the array. If there are nested objects, I want to concatenate the object names to represent the hierarchy.
const data =
[
{ id: 10, obj: {name: "Name1", obj2: {name2: "Name2", test: "Test"}}}
...
]
Final result = ["id", "obj.name", "obj.obj2.name2", "obj.obj2.test"]
Note: The first object includes all the keys needed, no further looping required to fetch KEYS.
My objective is to extract all keys from the initial object in the array. When encountering nested objects, I want to concatenate the object names (e.g., obj.obj2key1).