简体   繁体   English

如何遍历嵌套对象中的特定键?

[英]How to loop through specific keys in nested object?

I want to pull specific parts (definitely not all) from this object: 我想从此对象中提取特定部分(绝对不是全部):

var metadata = {
    cat: {
        id: 'id',
        name: 'kitty',

    },    
    dog: {
        id: 'id',
        name: 'spot',
        owner: {
            name: 'ralph',
        }
    }    
    //tons of other stuff
};

I would like to do something like this: 我想做这样的事情:

var fields = ['cat.id', 'dog.name', 'dog.owner.name'];
fields.forEach( function(key) {
    console.log(metadata[key]); //obv doesn't work
});

This is a simplified scenario where I'm trying to validate specific fields in metadata. 这是一个简化的场景,其中我尝试验证元数据中的特定字段。 Is there a straightforward way to do this? 有没有简单的方法可以做到这一点?

Split the path to extract individual keys, then use a reducer to resolve the value, then map the results: 分割路径以提取单个键,然后使用化简器解析值,然后映射结果:

var path = function(obj, key) {
  return key
    .split('.')
    .reduce(function(acc, k){return acc[k]}, obj)
}

var result = fields.map(path.bind(null, metadata))
//^ ['id', 'spot', 'ralph']

Now you can log them out if you want: 现在,您可以根据需要注销它们:

result.forEach(console.log.bind(console))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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