Elevant Elevant - 5 months ago 24
Javascript Question

Search object for object containing 2 values?

I have a Object which holds the configs of each product variant basically i want to be able to search which object has 2 specific values and then grab the v_id value for it, there will ONLY be 1 result.

code:

//object
product_1: {
p_id: 11, // Pendant Conicol
variants: {
v_1: { v_id:397, color:"gold", size:"20|30" },
v_2: { v_id:396, color:"gold", size:"20|40" },
v_3: { v_id:395, color:"gold", size:"20|50" },
v_4: { v_id:394, color:"gold", size:"25|25" }
}
}

getVariantId: function() {
var results = []; // There will only be 1 result so maybe dont need array?
var searchFor = "gold and 20|50";
//Loop here?
console.log(results.v_id);
}

Answer
var results = Object.keys(product_1.variants).map(function (key) {
    return product_1.variants[key];
}).filter(function (object) {
    return object.color === 'gold' && object.size === '20|50';
});

Where product_1.variants is a reference to the variants object.

Comments