简体   繁体   中英

How can I get keys from nested object?

I have a javascript object with nested objects inside:

{
    "common": {
      "setting1": "Value 1",
      "setting2": 200,
      "setting3": true,
      "setting6": {
        "key": "value",
        "doge": {
          "wow": ""
        }
      }
    },
    "group1": {
      "baz": "bas",
      "foo": "bar",
      "nest": {
        "key": "value"
      }
    },
    "group2": {
      "abc": 12345,
      "deep": {
        "id": 45
      }
    }
  }

and I have to get all keys as nested array.

I've tried this function:

function getKeys(obj) {                                                                                                                                
  return Object.keys(obj).map((key, keys) => {                                                                                                      
    if (typeof obj[key] !== 'object') return key;                                                                                                    
    return [key, getKeys(obj[key])];                                                                                               
  });                                                                                                                                                  
}    

 

And got this: //

[
  [ 'common', [ 'setting1', 'setting2', 'setting3', [Array] ] ],
  [ 'group1', [ 'baz', 'foo', [Array] ] ],
  [ 'group2', [ 'abc', [Array] ] ]
]

Instead of expected result like this:

    [
  [ 'common', [ 'setting1', 'setting2', 'setting3','setting6', ['key','doge', ['wow']],
  [ 'group1', [ 'baz', 'foo', ['nest', ['key'] ],
  [ 'group2', [ 'abc', 'deep', ['id'] ] ]
    ]

etc.

Help me please

You can use reduce on Object.entries and create a recursive function.

 const data = {"common":{"setting1":"Value 1","setting2":200,"setting3":true,"setting6":{"key":"value","doge":{"wow":""}}},"group1":{"baz":"bas","foo":"bar","nest":{"key":"value"}},"group2":{"abc":12345,"deep":{"id":45}}} function getKeys(data) { return Object.entries(data).reduce((r, [key, value]) => { r.push(key) if (typeof value === 'object') r.push(getKeys(value)) return r }, []) } console.log(getKeys(data))

Try this

function getKeys (obj) {
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++){
        const key = keys[i];
        if (typeof obj[key] === 'object') {
            keys.splice(i+1, 0, getKeys(obj[key]));
            i++;
        }
    }
    return keys
}

result:

'["common",["setting1","setting2","setting3","setting6",["key","doge",["wow"]]],"group1",["baz","foo","nest",["key"]],"group2",["abc","deep",["id"]]]'

Not the most optimised solution probably but should work.

Thanks, both options worked! I just had to add null check in if (typeof obj[key] === 'object') because of the TypeError: Cannot convert undefined or null to object const keys = Object.keys(obj); (one of the values was null and "The typeof null returns 'object', which is historical bug in JavaScript that may never be fixed.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM