So I have an array of values which I need to find:
const values = [ 'v4', 'w1']
And there is the array of objects where I need to look into:
const nodes = [
{
"node": {
"options": [
{
"name": "Key1",
"value": "v1"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v1"
},
{
"name": "Key2",
"value": "w2"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v2"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v2"
},
{
"name": "Key2",
"value": "w2"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v3"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v3"
},
{
"name": "Key2",
"value": "w2"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v4"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v4"
},
{
"name": "Key2",
"value": "w2"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v5"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
{
"node": {
"options": [
{
"name": "Key1",
"value": "v5"
},
{
"name": "Key2",
"value": "w2"
}
]
}
}
]
And I basically need to find which is the node that matches the values array (in this example, the result should be nodes[6]
{
"node": {
"options": [
{
"name": "Key1",
"value": "v4"
},
{
"name": "Key2",
"value": "w1"
}
]
}
},
values
array will always have the length of node.options
, but one of the values can be undefined
in which case the first occurrence of the defined value should be returned.
e.g. values = [ undefined, 'w1']
-> nodes[0]
I managed to do something like
const result = nodes.find(
(node) =>
options[0].value === values[0] &&
options[1].value === values[1]
);
But his won’t work if options has length different than 2.
Some other things I tried: (but seem to no be working)
nodes.find((node) => node.options.find(item => {
values.map(opt => opt === item.value)
}))
nodes.find((node) => node.options.filter(item => {
return values.includes(item.value)
}))