4 回答

TA貢獻1827條經驗 獲得超4個贊
您可以使用eval()它評估字符串并將其視為節(jié)點/變量,假設您已經聲明了一個與評估的字符串等效的變量名稱。
let data = {
hello: {
world: {
that: {
is: {
something: [1, 2, 3, 4, 5]
}
}
}
},
that: {
is: {
something: {
different: "Noo!!!"
}
}
}
}
let pre_build_keys_1 = "data.hello.world.that.is.something"
let pre_build_keys_2 = "data.that.is.something.different"
console.log(eval(pre_build_keys_1))
console.log(eval(pre_build_keys_2))

TA貢獻1900條經驗 獲得超5個贊
假設數(shù)據(jù)結構穩(wěn)定且與示例一致,我認為您已經完成了所有艱苦的工作!在這一點上,您可以評估您想要的確切路徑并返回它。
console.log(eval("data.hello.world.that.is.something"));
console.log(eval("data.that.is.something.different"));

TA貢獻1856條經驗 獲得超5個贊
您可以像下面這樣創(chuàng)建函數(shù)并使用數(shù)組getData
傳遞data
對象。單擊此處了解更多關于used in 的信息。key
reduce
getData
function getData(data, keys) {
return keys.reduce((acc, key) => acc[key], data);
}
let pre_build_keys_1 = ["hello", "world", "that", "is", "something"];
let pre_build_keys_2 = ["that", "is", "something", "different"]
let data = {
hello: {
world: {
that: {
is: {
something: [1, 2, 3, 4, 5]
}
}
}
},
that: {
is: {
something: {
different: "Noo!!!"
}
}
}
};
console.log(getData(data, pre_build_keys_1)); // [1, 2, 3, 4, 5]
console.log(getData(data, pre_build_keys_2)); // Noo!!!

TA貢獻1836條經驗 獲得超13個贊
你可以創(chuàng)建一個代理對象來處理從對象中獲取適當?shù)捻椖浚缓竽憧梢詮淖置嫔献鰀ata['hello.world.that.is.something']來獲取你想要的東西,就像這樣:
let real_data = {
hello: {
world: {
that: {
is: {
something: [1, 2, 3, 4, 5]
}
}
}
},
that: {
is: {
something: {
different: "Noo!!!"
}
}
}
}
const handler = {
get: function(target, prop, receiver) {
let parsed;
try {
parsed = JSON.parse(prop);
} catch (e) {
if (prop.startsWith('[')) {
parsed = prop.substring(1, prop.length - 1);
parsed = parsed.split(', ').join(',').split(',');
} else {
parsed = prop.split('.');
}
}
return parsed.reduce((carry, current) => carry[current], target);
}
};
const data = new Proxy(real_data, handler);
console.log(data['hello.world.that.is.something'])
console.log(data['[that, is, something, different]'])
console.log(data['["that", "is", "something", "different"]'])
添加回答
舉報