我有一个接受属性名的函数
func(propertyName) {
return object[propertyName];
}
所以通过调用func('value')
将返回object.value
然而对象是复杂的,所以它有内部道具
我想做的是能够做到func('property1.property2')
最好的方法是什么?
reduce
和可选链操作符的组合确保了对任何传递的类型/对象的任何传递的属性键路径的故障安全实现和故障安全访问…
function getValueByKeyPath(obj, path) {
return String(path)
.split('.')
.reduce((value, key) => value?.[key], Object(obj))
}
const sampleData = {
foo: {
value: 'foo',
bar: {
value: 'bar',
baz: {
value: 'baz',
},
},
},
};
console.log(
"getValueByKeyPath(sampleData, 'foo.bar.baz') ...",
getValueByKeyPath(sampleData, 'foo.bar.baz')
);
console.log(
"getValueByKeyPath(sampleData, 'foo.bar.baz.value') ...",
getValueByKeyPath(sampleData, 'foo.bar.baz.value')
);
console.log(
"nfail safe ... getValueByKeyPath(sampleData, 'foo.biz.baz.value') ...",
getValueByKeyPath(sampleData, 'foo.biz.baz.value')
);
console.log(
"nfail safe ... getValueByKeyPath('', 'toString') ...",
getValueByKeyPath('', 'toString')
);
console.log(
"fail safe ... getValueByKeyPath(null, '') ...",
getValueByKeyPath(null, '')
);
console.log(
"fail safe ... getValueByKeyPath() ...",
getValueByKeyPath()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
上面的方法可以扩展到带有引号和未引号键的括号表示法,例如嵌套/混合对象和基于数组的数据结构。然后,在捕获括号内的值时,不会在任何点上拆分键路径,而是在任何开、闭括号上拆分键路径。这个分割操作的结果需要从一些错误的工件中清除出来,减少部分保持不变…
function getValueByKeyPath(obj, path) {
return String(path)
.split(/.|[['"]?([^'"]]*)['"]?]/)
.filter(elm => !!elm)
.reduce((value, key) => value?.[key], Object(obj))
}
const sampleDataA = {
foo: {
value: 'foo',
bar: {
value: 'bar',
baz: {
value: 'baz',
},
},
},
};
const sampleDataB = {
foo: {
bar: [{
baz: {
value: 'baz',
biz: {
value: 'biz',
},
}
}, {
buzz: {
value: 'buzz',
booz: {
value: 'booz',
},
}
}],
},
};
console.log(
"getValueByKeyPath(sampleDataA, 'foo.bar.baz.value') ...",
getValueByKeyPath(sampleDataA, 'foo.bar.baz.value')
);
console.log(
"getValueByKeyPath(sampleDataA, 'foo.bar["baz"].value') ...",
getValueByKeyPath(sampleDataA, 'foo.bar["baz"].value')
);
console.log(
"getValueByKeyPath(sampleDataB, 'foo.bar[1]["buzz"].booz') ...",
getValueByKeyPath(sampleDataB, 'foo.bar[1]["buzz"].booz')
);
console.log(
"fail safe ... getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz') ...",
getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
try this:
示例数据:a={b:{c:"hellooo"}};
功能:function getValue(object,propertyName){ return propertyName.split(".").reduce((a,c)=>a[c],object); }
反应:
getValue(a,"b.c") = hellooo