I have a Javascript object as below;
grouped = {
"field1": [{
"path": "field1",
"type": "min",
"message": "Invalid"
}, {
"path": "field1",
"type": "api-error",
"message": "Invalid"
}],
"field2": [{
"path": "field2",
"type": "min",
"message": "Invalid length"
}, {
"path": "field2",
"type": "api-error",
"message": "API error"
}]
}
I want to combine them based on unique "message" value and then run the following code on the result
for (const {path,type,message} of result) {
setError(path, type, message);
}
So, in the above case,
- For "field1", since "Invalid" is common string message, setError should be called on result with message "Invalid",
- while for "field2", since the string messages are different, the message string should be concatenated and then passed to setError as "Invalid lengthnInvalid"
Again, the number of fields within "grouped" are dynamic. I have shown here just as an example with 2 fields.
Is there an ES6 way of getting this?
2
Answers
It seems you want one result per key in the outer object. So you could iterate the outer object values (which are arrays) and then take the first object from that array, and combine it with a new message property that is the concatenation of unique messages in that array (using
Set
):If I understand you correctly, you could check if they all have the same message, if so, overwrite the message with a
joined
version of all of them, then loop over that to cal setErrorGives