Skip to content Skip to sidebar Skip to footer

Get The Key Of A Nested Object

I need a simple method to get the key of a nested object, e.g. description. This is my structure: let data = [ { name: 'Apple', id: 1, alt: [{ name: 'fruit1', descrip

Solution 1:

You can use Object.keys(x) to list the keys for any arbitrary object. Regarding the nesting, it is just a case of knowing which of the nested indicies you wish to list fields for and supplying it.

You might want to consider something like this


Solution 2:

To get the keys of a nested object:

Object.keys(data[0].alt[0]) => results in string array ["name","description"] - not neccessarily in this order.

To get value of description key:

data[0].alt[0].description => results in tbd1 string.

To get an array of all descriptions:

data.map(obj => obj.alt[0].description).

Didn't know what you meant, so gave you all the options I could think of.


Solution 3:

If you want the keys, including nested keys, you can recursively traverse the array/objects like so.

There are two optional parameters that allow you to:

  • Ignore the array part i.e. skipArrays
  • Whether to keep the parent object keys i.e. keepObjKeys.

const isObject = (obj) => obj != null && obj.constructor.name === "Object";

let data = [
  { name: "Apple",     id: 1, alt: [{ name: "fruit1", description: "tbd1" }] },
  { name: "Banana",    id: 2, alt: [{ name: "fruit2", description: "tbd2" }] },
  { name: "Blueberry", id: 3, alt: [{ name: "fruit3", description: "tbd3" }] }
];

console.log(getKeys(data, false, false));
console.log(getKeys(data, true, true));

function getKeys(obj, keepObjKeys, skipArrays, keys=[], scope=[]) {
  if (Array.isArray(obj)) {
    if (!skipArrays) scope.push('[' + obj.length + ']');
    obj.forEach((o) => getKeys(o, keepObjKeys, skipArrays, keys, scope), keys);
  } else if (isObject(obj)) {
    Object.keys(obj).forEach((k) => {
      if ((!Array.isArray(obj[k]) && !isObject(obj[k])) || keepObjKeys) {
        let path = scope.concat(k).join('.').replace(/\.\[/g, '[');
        if (!keys.includes(path)) keys.push(path);
      }
      getKeys(obj[k], keepObjKeys, skipArrays, keys, scope.concat(k));
    }, keys);
  }
  return keys;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Solution 4:

May help you

let keys = Object.keys(yourObject);

keys array contains name,description


Post a Comment for "Get The Key Of A Nested Object"