Let's start with an object:
const oData = {
name: 'Dragon',
weapon: 'fire-breath',
likes: 'Gold, Flying, Power',
dislikes: 'Ice, Humans, Knights'
};
This object is then passed to the following function:
fConvertValuesToArrays(obj) {
for (const i in obj) {
obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]];
}
return obj;
},
The above function successfully transforms all the values into arrays. Now, I have a requirement where this transformation should only occur if the value matches any of the items in this array:
const aNamesToMatch = [ 'likes', 'dislikes' ];
Is there a way to incorporate this check within the existing function or should I create a separate one and call it from fConvertValuesToArrays
?
If so, how can this be implemented?
I attempted to introduce an if statement prior to the ternary operation but it did not behave as anticipated:
fConvertValuesToArrays(obj) {
for (const i in obj) {
if ( i.likes || i.dislikes ) {
obj[i] = Array.isArray(obj[i]) ? obj[i] : [obj[i]];
}
}
return obj;
},