我试图使用动态名称访问对象的属性。这可能吗?
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!"
当前回答
对于任何想要设置嵌套变量值的人来说,下面是如何做的:
const _ = require('lodash'); //import lodash module
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
文档:https://lodash.com/docs/4.17.15
另外,如果您想获得一个值,可以查看文档:https://lodash.com/docs/4.17.15#get
其他回答
这是我的解决方案:
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'})
您可以使用括号符号动态访问对象的属性。这看起来像obj[yourKey],然而JavaScript对象并不是为动态更新或读取而设计的。它们打算在初始化时定义。
如果你想动态分配和访问键值对,你应该使用映射。
const yourKey = 'yourKey'; //初始化它的值 const map1 = new Map([ (“yourKey”、“yourValue”) ]); //初始化为空,然后动态赋值 const map2 = new Map(); map2。集(yourKey yourValue); console.log (map1.get (yourKey)); console.log (map2.get (yourKey));
你可以在Javascript中使用getter
getter文档
检查对象内部是否存在有问题的属性, 如果它不存在,就从窗口拿走
const something = {
get: (n) => this.n || something.n || window[n]
};
您应该使用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)
下面是一个ES6示例,说明如何使用通过连接两个字符串动态生成的属性名访问对象的属性。
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
这称为计算属性名