Home > Net >  How to tell if a JavaScript object contains values from an array of strings
How to tell if a JavaScript object contains values from an array of strings

Time:02-01

I have a JavaScript object and I want to return true or false if strings from an array of strings are found inside the object somewhere.

For example:

object: { status: ‘draft’, type: ‘celebration’, color: ‘blue’, size: ‘medium’ }

Array from which to match strings = [‘blue’, ‘celebration’]

So since the object contains both ‘blue’ and ‘celebration’ it would return true. But if the array was [‘green’, ‘celebration’] it would return false, because ‘green’ is not inside the object.

If I was just finding one string inside the object, I know I can use .includes() but I need to find if several values exist.

CodePudding user response:

You can get all the property values of the object with Object.values. Then use Array#every in conjunction with Array#includes to ensure that each search value exists.

let object = { status: 'draft', type: 'celebration', color: 'blue', size: 
'medium' }
let search = ['blue', 'celebration'];

let values = Object.values(object);
let res = search.every(x => values.includes(x));
console.log(res);

CodePudding user response:

Here is my solution

function detect(obj, arr) {
  const valuesFromObject = Object.values(obj);
  return arr.every(value => valuesFromObject.includes(value));
}

const inputObject = {
  status: 'draft',
  type: 'celebration',
  color: 'blue',
  size: 'medium'
};

const case_1 = detect(inputObject, ['blue', 'celebration']);
const case_2 = detect(inputObject, ['green', 'celebration']);
console.log(case_1, case_2);

CodePudding user response:

This solution build a found array with all values matching the search array:

const search = ['blue', 'celebration'];
const input = {
  object1: { status: 'draft', type: 'celebration', color: 'blue', size: 
'medium' },
  object2: { status: 'draft', type: 'celebration', color: 'green', size: 
'medium' }
};
Object.keys(input).forEach(name => {
  let found = Object.values(input[name]).filter(val => search.indexOf(val) >= 0);
  console.log(name, found.length === search.length);
});

Output:

object1 true
object2 false
  • Related