简体   繁体   English

如何通过javascript中的单个字符串键获取嵌套对象的值?

[英]How to get values of nested object by a single string key in javascript?

There is an object info which describes as below:-有一个对象info描述如下:-

    let info = {
        "person" : {
            "name" : "Something",
            "age" : 1
        }
    }

I want to access the property name and I want to access it like info["person.name"] , how it can be done?我想访问属性name ,我想像info["person.name"]一样访问它,怎么做?

You could use a proxy like this:您可以使用这样的代理:

 const customAccessor = obj => new Proxy(obj, { set(_, keys, value) { const recSet = (object, [key, ...remaining], value) => { if (remaining.length === 0) { object[key] = value; } else { recSet(object[key], remaining, value); } } recSet(_, keys.split('.'), value); }, get(_, keys) { const recGet = (object, [key, ...remaining]) => { if (remaining.length === 0) { return object[key]; } else { return recGet(object[key], remaining); } } return recGet(_, keys.split('.')); } }); const info = customAccessor({ "person": { "name": "Something", "age": 1 } }); console.log(info['person.age']); info['person.age'] = 10; console.log(info['person.age']);

following works以下作品

info['person']['name']
info.person['name']
info['person'].name
info.person.name

and if you really want to keep it in one string I suggest writing a small function that splits by "."如果你真的想把它保存在一个字符串中,我建议编写一个由“.”分割的小函数。 and then goes through the same steps as above然后执行与上述相同的步骤

function getValue(obj,path){
     for(let pathPart of path.split('.')){
         obj=obj[pathPart];
     }
     return obj;
}

Try this:尝试这个:

 function getProperty(obj, property) { var locArr = property.split("."), returnVal = obj; for (let i=0; i<locArr.length; i++) { returnVal = returnVal[locArr[i]] } return returnVal } console.log(getProperty({ "person" : { "name" : "Something", "age" : 1 } }, "person.name"))

You can simply use references您可以简单地使用references

 let info = { "person" : { "name" : "Something", "age" : 1 } } let findByName = (name) => { let arr = name.split('.') let ref = info arr.forEach(e => { ref = ref[e] ? ref[e]: {} }) return ref } console.log(findByName("person.name")) console.log(findByName("person.age")) console.log(findByName("person.age.someProp")) console.log(findByName("person.someProp"))

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

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