Consider below obj1 and obj2
const obj1 =
{
“array”:
[{"path": "time.day"},
{"path": “human.gender”},
{“nestedArray”: [{"path": "time.Month"},{"path": "time.Day"}]}
]
}
const obj2 =
{"time":{"day": "String”,"Month": “String”},“human”:{“gender”: “String”}}
Now I need to loop through array and nested Array in obj1 and check obj1 arrays 'path' matches with key-value pairs in obj2.how can this be done?
CodePudding user response:
An example:
const obj1 = {
array: [{
path: "time.day"
},
{
path: "human.gender"
},
{
nestedArray: [{
path: "time.Month"
}, {
path: "time.Day"
},
{
nestedArray: [{
path: "human.foo"
}, ]
}
]
}
]
}
const obj2 = {
time: {
day: "String",
Month: "String"
},
human: {
gender: "String",
foo: "bar",
}
}
const data = [];
function recursion(e) {
if (e.path) {
const values = e.path.split('.');
const path = obj2[values[0]][values[1]]
if (path) {
data.push(values[0]);
data.push(values[1]);
}
} else if (e.nestedArray) {
e.nestedArray.forEach((element) => {
recursion(element)
});
}
}
obj1.array.forEach((e) => {
recursion(e)
});
console.log(data)
IMPORTANT
This code will work only if the conditions to add values to the array is when the whole path is correct - not just the part of it (and the path is composed of two parts)
CodePudding user response:
You can split the string and check inside obj2.
const obj1 = {
array: [
{ path: "time.day" },
{ path: "human.gender" },
{ nestedArray: [{ path: "time.Month" }, { path: "time.Day" }] },
],
};
const obj2 = {
time: { day: "String", Month: "String" },
human: { gender: "String" },
};
const find = (arr, obj2) => {
const result = [];
arr.forEach((a) => {
if (a?.path) {
const [start, end] = a?.path?.split(".") ?? [];
if (obj2[start]) {
result.push(start);
if (obj2[start][end]) result.push(end);
}
} else if (a?.nestedArray) {
result.push(...find(a.nestedArray, obj2));
}
});
return result;
};
console.log(find(obj1.array, obj2));