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

时间:2019-03-30 14:29:18

标签: javascript

有一个对象info,其描述如下:-

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

我想访问属性name,并且想像info["person.name"]一样访问它,如何完成?

4 个答案:

答案 0 :(得分:1)

您可以使用这样的代理服务器:

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

答案 1 :(得分:0)

以下作品

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

如果您确实希望将其保存在一个字符串中,建议您编写一个小函数,以“。”分隔。然后执行与上述相同的步骤

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

答案 2 :(得分:0)

尝试一下:

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

答案 3 :(得分:0)

您可以简单地使用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"))