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');
>Solution :
Try this:
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"
};
const dependency = [
{"field": "font-color", "value": "#fff"},
{"field": "font-color", "value": "#222"}
];
let filtered = optionData['fields'].filter(field => {
return !dependency.some(dependency => {
return dependency['field'] === field['id'] && dependency['value'] === field['value'];
});
});
console.log(filtered);
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