Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if part of an object contains another entire object

Tags:

javascript

I have a large object that is dynamic but it has a simple structure like below:

let numbers = {
    one:   true,
    two:   false,
    three: false,
    four:  true,
    five:  true,
    six:   false,
    seven: false,
    eight: false,
    nine:  false,
    ten:   false
};

and then an array of smaller object which are dynamic and could or could not contain values from the first object.

let input = [{ one: true, four: true, five: true}, { one: true, two: true, three: true, ten: true}];

So what I need is to see if all of the properties in the second object exactly match the corresponding properties in the first object. In the case above the first object would be a match but the second would fail since ten: true does not match the corresponding property in the first object.

This is what I've come up with but it seems very inefficient and I can't help but think there's a better way:

checkMatch(numbers, input) {

    for (let obj of input) {
        let count = 0;

        for (let key of obj) {
            if (numbers[key]) count++;
        }

        if (count == Object.keys(obj).length) console.log('match');
        else console.log('no match');
    }

}
like image 439
Mr.Smithyyy Avatar asked Oct 28 '25 11:10

Mr.Smithyyy


1 Answers

You could use Array#every() on Object.entries()

let numbers = {
    one:   true,
    two:   false,
    three: false,
    four:  true,
    five:  true,
    six:   false,
    seven: false,
    eight: false,
    nine:  false,
    ten:   false
};

let input = [{ one: true, four: true, five: true}, { one: true, two: true, three: true, ten: true}];

input.forEach(o=>{
   const isMatch = Object.entries(o).every(arr=> numbers[arr[0]] == arr[1])
   console.log( [isMatch,o] );
})
like image 147
charlietfl Avatar answered Oct 30 '25 01:10

charlietfl