0

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)

3
  • Just prepend object1. to these and you have your array literal? Commented Feb 7, 2020 at 0:46
  • You want to recursively collect all the keys from your nested object? Is that it? Commented Feb 7, 2020 at 0:46
  • 1
    Check out this related post stackoverflow.com/questions/34280216/… Commented Feb 7, 2020 at 0:47

4 Answers 4

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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"]

4 Comments

OP shows [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.
@StackSlave The question is unclear so I asked for clarification. Since it doesn't seem to be forthcoming, I answered what I understood the question to be. Thanks for the downvote. I've updated my answer to include a solution according to your interpretation of the question.
Thanks Robby, sorry for not clear on the question. I just need a key pair not values [a,b,c.d] (keys only)
@PraveenAlluri Added a snippet in the middle for the nested keys (with dot notation) scenario.
0

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, ''));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.