I am trying to convert the nested object to array
below is the example I am trying const object1 = { a: 'somestring', b: 42, c: { d : "y" } };
I want my result to be [a,b,c.d](needed keys not vlaues)
The function you're looking for is Object.keys()
You can find more data about it at:
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/keys
If you want the furthest value into the Object, then it's like:
function walkRecursive(walkable, walkFunc){
if(typeof walkable === 'object'){
let v;
if(walkable instanceof Array){
for(let i=0,l=walkable.length; i<l; i++){
v = walkable[i];
if(typeof v === 'object'){
walkRecursive(v, walkFunc);
}
else{
walkFunc(v, i, walkable);
}
}
}
else{
for(let i in walkable){
v = walkable[i];
if(typeof v === 'object'){
walkRecursive(v, walkFunc);
}
else{
walkFunc(v, i, walkable);
}
}
}
}
return
}
const a = [];
walkRecursive({a:'somestring', b:42, c:{d:'y'}}, (v, i, o)=>{
console.log('object: '+o);
console.log('property: '+i);
console.log('value: '+v);
console.log('+++++++++++++++++++++++++++++++++++++++++++');
a.push(v);
});
console.log('-------------------------------------------');
console.log(a);
The below collect() function uses Object.entries() and Array.prototype.reduce() to recursively collect all the keys from your object:
const collect = (x) => typeof x === 'object' && x !== null
? Object.entries(x).reduce((a, [k, v]) => [...a, k, ...collect(v)], [])
: [];
const keys = collect({ a: 'somestring', b: 42, c: { d : "y" } });
console.log(keys); // ["a", "b", "c", "d"]
If you want to collect nested keys (with dot notation):
const collect = (x, path) => typeof x === 'object' && x !== null
? Object.entries(x).reduce((a, [k, v]) => [
...a,
...collect(v, path ? `${path}.${k}` : k)], [])
: [path];
const keys = collect({ a: 'somestring', b: 42, c: { d : "y" } });
console.log(keys); // ["a", "b", "c.d"]
If you want to recursively collect values instead of keys:
const collect = (x) => typeof x === 'object' && x !== null
? Object.entries(x).reduce((a, [_, v]) => [...a, ...collect(v)], [])
: [x];
const values = collect({ a: 'somestring', b: 42, c: { d : "y" } });
console.log(values); // ["somestring", 42, "y"]
[a,b,c.d], so yeah, that's 3 elements with c.d being the last. Not only that, but those are just the properties. If you want those, they're in the last i argument of my example, by the way.Use Object.entries, reduce with recursive approach.
const obj = { a: 'somestring', b: 42, c: { d: "y" } };
const getKeysArr = (obj, prefix) => {
var arr = Object.entries(obj).reduce((acc, [key, value]) => {
if (["string","number"].includes(typeof value)) {
acc.push(prefix ? `${prefix}.${key}` : key);
} else {
acc.push(getKeysArr(value, key));
}
return acc;
}, []);
return arr.flat();
};
console.log(getKeysArr(obj, ''));
object1.to these and you have your array literal?