0

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"]];
1
  • What have you tried so far? What is not working? Recursion and Object.keys should help here. Commented Sep 14, 2022 at 7:03

2 Answers 2

2

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)

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

2 Comments

This code will run into an error if one of the values is "null" and might not work as expected if one of the values would be an array.
@ViktorLuft thanks for pointing that out. I've corrected the code to ensure it works correctly in those cases
1

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

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.