Reputation: 338
i need to go through an array of objects to compare 2 values. This is my array:
const data = [{
"uid": "6448ae4a79",
"title": "New Group",
"slug": "new-group",
"items": [
{
"uid": "8602b1cf1f",
"title": "New sub group",
"slug": "new-sub-group",
"items": [
{
"uid": "8b6f962ff1",
"_id": "5d9b453285a8982000b4a9e6",
"title": "fsds",
"choices": [
{
"uid": "a5ccb273a2",
"_id": "5d9b453285a8982000b4a9eb",
"type": null,
"text": "sd",
"label": null,
"value": null
},
{
"uid": "8ab0d45386",
"_id": "5d9b453285a8982000b4a9e8",
"type": null,
"text": "sdwewe",
"label": null,
"value": null
}
]
},
{
"uid": "290db30b53",
"_id": "5d9b699185a8982000b4aa1d",
"title": "czxczxc",
"logic": {
"viewControl": [
{
"action": "lock",
"group": "6448ae4a79",
"subGroup": "8602b1cf1f",
"question": "8b6f962ff1",
"equalTo": "8ab0d45386"
}
]
},
"choices": [
{
"uid": "3cce36d426",
"_id": "5d9b699185a8982000b4aa1f",
"type": 0,
"text": "wqewq",
"label": "dsfsd",
"value": null
}
]
}
]
}
]
}]
I have to compare items.items.logic.viewControl[0].equalTo with choices.uid. Eg: "equalTo": "8ab0d45386" === "uid": "8ab0d45386".
How can I do this? I tried filter, map and foreach and I couldn't do it at all
Upvotes: 0
Views: 44
Reputation: 2751
If your goal to check that viewControl.equalTo - is one of choices (from different items) - so the solution may look like this:
choices.uid
choices.uid
exists.const data = [{
"uid": "6448ae4a79",
"title": "New Group",
"slug": "new-group",
"items": [
{
"uid": "8602b1cf1f",
"title": "New sub group",
"slug": "new-sub-group",
"items": [
{
"uid": "8b6f962ff1",
"_id": "5d9b453285a8982000b4a9e6",
"title": "fsds",
"choices": [
{
"uid": "a5ccb273a2",
"_id": "5d9b453285a8982000b4a9eb",
"type": null,
"text": "sd",
"label": null,
"value": null
},
{
"uid": "8ab0d45386",
"_id": "5d9b453285a8982000b4a9e8",
"type": null,
"text": "sdwewe",
"label": null,
"value": null
}
]
},
{
"uid": "290db30b53",
"_id": "5d9b699185a8982000b4aa1d",
"title": "czxczxc",
"logic": {
"viewControl": [
{
"action": "lock",
"group": "6448ae4a79",
"subGroup": "8602b1cf1f",
"question": "8b6f962ff1",
"equalTo": "8ab0d45386"
}
]
},
"choices": [
{
"uid": "3cce36d426",
"_id": "5d9b699185a8982000b4aa1f",
"type": 0,
"text": "wqewq",
"label": "dsfsd",
"value": null
}
]
}
]
}
]
}];
// 1. Collect choices.uid
const choicesUids = {};
data.forEach((d) => {
d.items.forEach((i1) => {
i1.items.forEach((i2) => {
i2.choices.forEach(c => {choicesUids[c.uid]=true})
});
});
});
// 2. Check the logic
data.forEach((d, ix0) => {
d.items.forEach((i1, ix1)=>{
i1.items.forEach((i2, ix2)=>{
if(i2.logic && i2.logic.viewControl) {
i2.logic.viewControl.forEach((vc, ix3)=>{
console.log(`data[${ix0}].items[${ix1}].items[${ix2}].logic.viewControl[${ix3}].equalTo:${vc.equalTo} - is ${choicesUids[vc.equalTo]?'GOOD':'BAD'}`);
});
}
});
});
});
OUTPUT:
data[0].items[0].items[1].logic.viewControl[0].equalTo:8ab0d45386 - is GOOD
Upvotes: 1