Javascript reflection: Get nested objects path

前端 未结 3 685
感情败类
感情败类 2021-01-03 02:35

In this stackoverflow thread, i learnt you can get a object path via a simple string.

Accessing nested JavaScript objects with string key

consider the follow

3条回答
  •  佛祖请我去吃肉
    2021-01-03 03:27

    Just use recursion to walk the object.

    var person = {
        name: "somename",
        personal: {
            weight: "150",
            color: "dark",
            foo: {
                bar: 'bar',
                baz: 'baz'
            },
            empty: {
            }
        }
    };
    
    // however you want to do this
    var isobject = function(x){
        return Object.prototype.toString.call(x) === '[object Object]';
    };
    
    var getkeys = function(obj, prefix){
        var keys = Object.keys(obj);
        prefix = prefix ? prefix + '.' : '';
        return keys.reduce(function(result, key){
            if(isobject(obj[key])){
                result = result.concat(getkeys(obj[key], prefix + key));
            }else{
                result.push(prefix + key);
            }
            return result;
        }, []);
    };
    
    var keys = getkeys(person);
    
    document.body.innerHTML = '
    ' + JSON.stringify(keys) + '
    ';

    Then use Array.prototype.map to massage the array of keys into your preferred format. Note the behaviour with person.personal.empty.

    This does seem like a strange way to store an object's keys. I wonder what your 'further use for it down the road' is.

提交回复
热议问题