Home > Software design >  javascript get object keys in array
javascript get object keys in array

Time:09-14

I have an object similar to the one below:

const obj = {
  "test1": {
    "test12": "val1",
    "test13": {
      "test131": "val1",
      "test132": "val2"
    }
  },
  "test2": "val2"
}

I want to receive the keys as follows:

const keys = [["test1", "test12", "test13", "test131", "test132"], ["test2"]];

CodePudding user response:

You can recursively process the entries in the object, collecting keys as you go and flattening the result arrays at all levels other than the top:

const obj = {
  "test1": {
    "test12": "val1",
    "test13": {
      "test131": "val1",
      "test132": "val2"
    }
  },
  "test2": null,
  "test3": {
    "test31": "val3"
  },
  "test4": {
    "test41": [1, 2, 3, 4]
  }
}

const getKeys = (obj, flat = false) => {
  const keys = Object.entries(obj)
    .map(([k, v]) => v instanceof Object && !(v instanceof Array) ? [k, ...getKeys(v, true)] : [k])
  return flat ? keys.flat() : keys
}

const allKeys = getKeys(obj)

console.log(allKeys)

CodePudding user response:

Here you go:

const obj = {
  "test1": {
    "test12": "val1",
    "test13": {
      "test131": "val1",
      "test132": "val2"
    }
  },
  "test2": "val2"
};

const mapToKeys = ([key, value]) => {
  if (Object.prototype.toString.call(value) === '[object Object]') {
    return [key, ...getKeys(value)];
  }
  return [key];
};
const getKeys = (o) => Object.entries(o).flatMap(mapToKeys);
const keys = Object.entries(obj).map(mapToKeys);

console.log(keys);

  • Related