I’m trying to filter out the corresponding font-colors from the field array in the object optionData:
{
"fields": [
{
"type": "color",
"id": "font-color",
"value": "#222",
"target": "font",
"dependency": []
},
{
"type": "color",
"id": "font-color",
"value": "#f00",
"target": "font",
"dependency": []
}
],
"textposition": {
"left": "12",
"top": "10"
},
"textsubtitle": "Kleur",
"additionalcosts": "4,99"
}
I have a dependency array where I keep the dependencies. In this case it consists only of font-colors and 2 values; #fff and #222. Therefore I want to filter out the #222.
Depencies:
[
{
"field": "font-color",
"value": "#fff"
},
{
"field": "font-color",
"value": "#222"
}
]
const optionData = {"fields":[{"type":"color","id":"font-color","value":"#222","target":"font","dependency":[]},{"type":"color","id":"font-color","value":"#f00","target":"font","dependency":[]}],"textposition":{"left":"12","top":"10"},"textsubtitle":"Kleur","additionalcosts":"4,99"};
console.log(optionData, 'optionData');
const dependency = [{"field":"font-color","value":"#fff"},{"field":"font-color","value":"#222"}];
console.log(dependency, 'dependency');
let filtered = optionData['fields'].filter(field => {
console.log(field, 'field');
return dependency.filter(dependency => {
console.log(dependency, 'dependency')
return dependency['field'] !== field['id'] && dependency['value'] !== field['value'];
})
})
console.log(filtered, 'filtered');
2
Answers
Try this:
The code uses the filter method to iterate over the optionData[‘fields’] array and keep only the objects that satisfy the filtering condition. The condition is implemented using the some method on the dependency array. It checks if there is at least one object in dependency that matches both the field and value of the current object in optionData[‘fields’]. The ! operator negates the result so that only objects that do not have a matching dependency are kept.
In the provided example, the filtered array will contain only the object with value: "#f00" since it does not match any of the dependencies in the dependency array
filter
uses a boolean (the result of a condition) to determine whether an element should be filtered or not, however your innerfilter
returns a new array so it’s not really suitable.There is another array method that you can use that does return a boolean:
some
. For each iterated field you can check to see ifsome
of the corresponding entries in the dependencies array are a match. If there is a match the method immediately breaks so that the whole dependency array doesn’t have to be iterated over.Additional documentation