如何获取对象字符串中对象的值
How do i get the value of an object in a object string
你好,我对此有点陌生,所以我想做的是
string = {
"string2": {
"value": ""
}
}
var path = ["string2","value"]
我能以某种方式获得路径的价值我尝试了很多东西但没有任何效果
您可以为此使用 Array.reduce():
const value = path.reduce((accum, key) => accum[key], string)
有几种方法。首先,可以使用循环一步步遍历路径如下:
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
let output = obj;
path.forEach(key => {
output = output[key];
});
console.log( output );
递归
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const trav = (o,p,i) => (i < p.length - 1) ? trav(o[p[i]],p,i+1) : o[p[i]];
console.log( trav(obj,path,0) );
新函数
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const output = (new Function(`return (obj.${path.join('.')})`))();
console.log( output );
你好,我对此有点陌生,所以我想做的是
string = {
"string2": {
"value": ""
}
}
var path = ["string2","value"]
我能以某种方式获得路径的价值我尝试了很多东西但没有任何效果
您可以为此使用 Array.reduce():
const value = path.reduce((accum, key) => accum[key], string)
有几种方法。首先,可以使用循环一步步遍历路径如下:
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
let output = obj;
path.forEach(key => {
output = output[key];
});
console.log( output );
递归
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const trav = (o,p,i) => (i < p.length - 1) ? trav(o[p[i]],p,i+1) : o[p[i]];
console.log( trav(obj,path,0) );
新函数
const obj = { "string2": { "value": "Message" } };
const path = [ "string2", "value" ];
const output = (new Function(`return (obj.${path.join('.')})`))();
console.log( output );