user12163165
user12163165

Reputation: 617

How to check for at least one object inside another object

I need to validate a form field.
this is the categories field inside my form.

categories = {
    category1: [ 
        { id: 1, quantity: 0 },
        { id: 2, quantity: 0 }
    ],
    category2: [ 
        { id: 3, quantity: 0 },
        { id: 4, quantity: 0 }
    ],
    category3: [ 
        { id: 5, quantity: 0 },
        { id: 6, quantity: 0 }  
    ]
}

this is how I check if AT LEAST ONE array element passes a test inside EACH category.

for (const category in categories) {
    let theOne = categories[category].some(product => product.quantity !== 0);
}

this way the form will be valid if at least one quantity inside EACH category will hold a value of 1.

// I DONT WANT THIS
categories = {
    category1: [ 
        { id: 1, quantity: 1 }, // at least one quantity value is 1
        { id: 2, quantity: 0 }
    ],
    category2: [ 
        { id: 3, quantity: 1 }, // at least one quantity value is 1
        { id: 4, quantity: 0 }
    ],
    category3: [ 
        { id: 5, quantity: 1 }, // at least one quantity value is 1
        { id: 6, quantity: 0 }  
    ]
}


// I NEED THIS
categories = {
    category1: [ 
        { id: 1, quantity: 1 }, // at least one quantity value is 1
        { id: 2, quantity: 0 }
    ],
    category2: [ 
        { id: 3, quantity: 0 }, // not needed
        { id: 4, quantity: 0 }
    ],
    category3: [ 
        { id: 5, quantity: 0 }, // not needed
        { id: 6, quantity: 0 }  
    ]
}

how is it possible to make it work for at least one category ?

Upvotes: 1

Views: 69

Answers (1)

basickarl
basickarl

Reputation: 40454

That is to check them all:

const categories = {
    category1: [{ id: 1, quantity: 0 }],
    category2: [{ id: 2, quantity: 1 }],
    category3: [{ id: 3, quantity: 0 }]
};

const didIPass = Object.values(categories).some((category) => {
    return category.some((subCategory) => subCategory.quantity !== 0);
});
console.log('Did I pass?', didIPass);

That is to check inside each specifically:

Object.entries(categories).forEach((entry) => {
    const key = entry[0];
    const value = entry[1];
    const didIPass = value.some((subCategory) => subCategory.quantity !== 0);
    console.log(`Did ${key} pass? ${didIPass}`);
});

Will produce the output:

Did I pass? true
Did category1 pass? false
Did category2 pass? true
Did category3 pass? false

Upvotes: 2

Related Questions