I have an object that contains multiple arrays of strings, like
const object = {
"arrayA": [
"A1",
"A2"
]
"arrayB": [
"B1",
"B2"
]
...
}
How can I use Javascript function or lodash to find if a given string exists in the object? Thanks
CodePudding user response:
- Using
Object#values
, get the list of arrays - Using
Array#some
, iterate over this list to check if any array has the string usingArray#includes
const checkForString = (obj = {}, str) =>
Object.values(obj).some(arr => arr.includes(str));
const object = { "arrayA": [ "A1", "A2" ], "arrayB": [ "B1", "B2" ] };
console.log( checkForString(object, "A1") );
console.log( checkForString(object, "B1") );
console.log( checkForString(object, "C1") );