我试图使用动态名称访问对象的属性。这可能吗?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
我试图使用动态名称访问对象的属性。这可能吗?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
当前回答
演示对象示例
let obj = {
name: {
first_name: "Bugs",
last_name: "Founder",
role: "Programmer"
}
}
的值的虚线字符串键
let key = "name.first_name"
函数
const getValueByDottedKeys = (obj, strKey)=>{
let keys = strKey.split(".")
let value = obj[keys[0]];
for(let i=1;i<keys.length;i++){
value = value[keys[i]]
}
return value
}
调用getValueByDottedKeys函数
value = getValueByDottedKeys(obj, key)
console.log(value)
输出
Bugs
const getValueByDottedKeys = (obj, strKey)=>{ 让键= strKey.split(".") Let value = obj[keys[0]]; (让我= 1,< keys.length;我+ +){ Value = Value [key [i]] } 返回值 } 让obj = { 名称:{ first_name:“虫子”, last_name:“创始人”, 作用:“程序员” } } Let key = "name.first_name" value = getValueByDottedKeys(obj, key) console.log(值)
其他回答
这是我的解决方案:
function resolve(path, obj) {
return path.split('.').reduce(function(prev, curr) {
return prev ? prev[curr] : null
}, obj || self)
}
使用例子:
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// or even use array indexes
// (someObject has been defined in the question)
resolve("part.0.size", someObject)
// returns null when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
你可以在Javascript中使用getter
getter文档
检查对象内部是否存在有问题的属性, 如果它不存在,就从窗口拿走
const something = {
get: (n) => this.n || something.n || window[n]
};
演示对象示例
let obj = {
name: {
first_name: "Bugs",
last_name: "Founder",
role: "Programmer"
}
}
的值的虚线字符串键
let key = "name.first_name"
函数
const getValueByDottedKeys = (obj, strKey)=>{
let keys = strKey.split(".")
let value = obj[keys[0]];
for(let i=1;i<keys.length;i++){
value = value[keys[i]]
}
return value
}
调用getValueByDottedKeys函数
value = getValueByDottedKeys(obj, key)
console.log(value)
输出
Bugs
const getValueByDottedKeys = (obj, strKey)=>{ 让键= strKey.split(".") Let value = obj[keys[0]]; (让我= 1,< keys.length;我+ +){ Value = Value [key [i]] } 返回值 } 让obj = { 名称:{ first_name:“虫子”, last_name:“创始人”, 作用:“程序员” } } Let key = "name.first_name" value = getValueByDottedKeys(obj, key) console.log(值)
我也遇到了同样的问题,但是lodash模块在处理嵌套属性时受到了限制。我按照递归后代解析器的思想编写了一个更通用的解决方案。该解决方案适用于以下要点:
递归下降对象解引用
您应该使用JSON。解析,看看https://www.w3schools.com/js/js_json_parse.asp
const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)