我试图使用动态名称访问对象的属性。这可能吗?
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!"
当前回答
这是我的解决方案:
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'})
其他回答
演示对象示例
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(值)
ES5 //检查深嵌套变量
这段简单的代码可以检查嵌套深度的变量/值是否存在,而不需要检查每个变量…
var getValue = function( s, context ){
return Function.call( context || null, 'return ' + s )();
}
Ex. -嵌套很深的对象数组:
a = [
{
b : [
{
a : 1,
b : [
{
c : 1,
d : 2 // we want to check for this
}
]
}
]
}
]
而不是:
if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 ) // true
我们现在可以:
if( getValue('a[0].b[0].b[0].d') == 2 ) // true
干杯!
你可以在Javascript中使用getter
getter文档
检查对象内部是否存在有问题的属性, 如果它不存在,就从窗口拿走
const something = {
get: (n) => this.n || something.n || window[n]
};
我遇到过这样的情况,我想把对象属性的“地址”作为数据传递给另一个函数,并填充对象(使用AJAX),从地址数组进行查找,并在另一个函数中显示。我不能使用点表示法而不做字符串杂技,所以我认为一个数组可能是很好的传递代替。我最终做了一些不同的事情,但似乎与这篇文章有关。
这是一个类似于我想要数据的语言文件对象的示例:
const locs = {
"audioPlayer": {
"controls": {
"start": "start",
"stop": "stop"
},
"heading": "Use controls to start and stop audio."
}
}
我希望能够传递一个数组,如:["audioPlayer", "controls", "stop"]来访问语言文本,在这种情况下是"stop"。
我创建了这个小函数,它查找“最不特定的”(第一个)地址参数,并将返回的对象重新分配给自己。然后它准备查找下一个最特定的地址参数(如果存在的话)。
function getText(selectionArray, obj) {
selectionArray.forEach(key => {
obj = obj[key];
});
return obj;
}
用法:
/* returns 'stop' */
console.log(getText(["audioPlayer", "controls", "stop"], locs));
/* returns 'use controls to start and stop audio.' */
console.log(getText(["audioPlayer", "heading"], locs));
下面是一个ES6示例,说明如何使用通过连接两个字符串动态生成的属性名访问对象的属性。
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
这称为计算属性名