3 回答
TA贡献1795条经验 获得超7个赞
您可以使用 aObject.keys循环遍历dataPath对象。然后你split的价值,并使用它一个for 循环并跟踪data.
let nestedObj = {
"property1": {
"subProperty1": {
"data": "This is the data for property1 > subProperty1"
}
},
"property2": {
"subProperty1": {
"anotherSubProperty1": {
"data": "This is the data for property2 > subProperty1 > anotherSubProperty1"
}
},
"subProperty2": {
"anotherSubProperty1": {
"data": "This is the data for property2 > subProperty2 > anotherSubProperty1"
}
}
},
"property3": {
"subProperty1": {
"data": "This is the data for property3 > subProperty1"
}
}
}
let dataPath = {
"property1": "subProperty1.data",
"property2": "subProperty2.anotherSubProperty1.data",
"property3": "subProperty1.data",
}
let properties = ["property1", "property2", "property3"]
for (let property of properties) {
let path = dataPath[property].split('.')
let data = nestedObj[property]
for (let i = 0; i < path.length; i++) {
data = data[path[i]]
if (i + 1 === path.length) {
console.log(data)
}
}
}
TA贡献1851条经验 获得超5个赞
lodash 的_.get功能正是您想要的。您可以查看源代码以查看实现。
const nestedObj = { "property1":{ "subProperty1": { "data": "This is the data for property1 > subProperty1" } }, "property2":{ "subProperty1": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty1 > anotherSubProperty1" } }, "subProperty2": { "anotherSubProperty1": { "data": "This is the data for property2 > subProperty2 > anotherSubProperty1" } } }, "property3":{ "subProperty1": { "data": "This is the data for property3 > subProperty1" } } }
const dataPath = { "property1": "subProperty1.data", "property2": "subProperty2.anotherSubProperty1.data", "property3": "subProperty1.data", }
let props = ["property1", "property2", "property3"];
props.forEach(property => {
const nestedObjAtProperty = nestedObj[property]; // { "subProperty1": { "data": "This is the data for property1 > subProperty1" } }
const dataPathForProperty = dataPath[property]; // "subProperty1.data"
const data = _.get(nestedObjAtProperty, dataPathForProperty); // "This is the data for property1 > subProperty1"
console.log(data);
}
添加回答
举报