我试图使用动态名称访问对象的属性。这可能吗?

const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"

当前回答

在javascript中,我们可以访问:

点表示法- foo.bar 方括号- foo[someVar]或foo["string"]

但是只有第二种情况允许动态访问属性:

var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}

var name = "pName"
var num  = 1;

foo[name + num]; // 1

// -- 

var a = 2;
var b = 1;
var c = "foo";

foo[name + a][b][c]; // bar

其他回答

通过引用查找对象,字符串, 注意,确保你传递的对象是克隆的,我使用cloneDeep从lodash

如果对象看起来像

const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]

路径看起来像这样

const objectPath = ['data',1,'person',name','last']

然后调用下面的方法,它将按给定的路径返回子对象

const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"


const findObjectByPath = (objectIn: any, path: any[]) => {
    let obj = objectIn
    for (let i = 0; i <= path.length - 1; i++) {
        const item = path[i]
        // keep going up to the next parent
        obj = obj[item] // this is by reference
    }
    return obj
}

您应该使用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)

您可以使用括号符号动态访问对象的属性。这看起来像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));

演示对象示例

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 get

_.get(object, 'a[0].b.c');