I have such object:
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;
}
I want to get object by name values path:
console.log(getObjectByNamePath('ob_2.ob_2_1.ob_3_1', obj))
I tried this, but it doesn't work correct and i feel that there is more elegant way to achieve what i want. Thanks.