我有这样的对象:
var obj = [
{
name: 'ob_1',
childFields: [],
},
{
name: 'ob_2',
childFields: [
{
name: 'ob_2_1',
childFields: [
{
name: 'ob_3_1',
childFields: [],
test: 124
},
],
},
],
},
]
function getObjectByNamePath(path, fieds) {
const pathArr = path.split('.');
const result = fieds.find(field => {
if (pathArr.length > 1) {
if (field.name === pathArr[0] && field.childFields.length) {
const newPath = pathArr.slice(1, pathArr.length).join('.');
return getObjectByNamePath(newPath, field.childFields);
}
return false;
} else {
if (field.name === pathArr[0]) {
return true;
} else {
return false;
}
}
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
我想通过名称值路径获取对象:
console.log(getObjectByNamePath('ob_2.ob_2_1.ob_3_1', obj))
Run Code Online (Sandbox Code Playgroud)
我尝试过这个,但它不正确,我觉得有更优雅的方式来实现我想要的.谢谢.
您可以迭代childFields并找到name此级别,然后获取下一级别名称.
function getObjectByNamePath(path, array) {
return path
.split('.')
.reduce(
({ childFields = [] } = {}, name) => childFields.find(o => o.name === name),
{ childFields: array }
);
}
var obj = [{ name: 'ob_1', childFields: [], }, { name: 'ob_2', childFields: [ { name: 'ob_2_1', childFields: [ { name: 'ob_3_1', childFields: [], test: 124 }] }] }];
console.log(getObjectByNamePath('ob_2.ob_2_1.ob_3_1', obj));
console.log(getObjectByNamePath('ob_1', obj));
console.log(getObjectByNamePath('foo.bar', obj));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |