我有一个Object,它包含每个产品变体的配置,基本上我希望能够搜索哪个对象有2个特定值,然后获取它的v_id值,只有1个结果。
代码:
//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);
}
答案 0 :(得分:0)
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';
});
其中product_1.variants
是对variant对象的引用。
答案 1 :(得分:0)
var 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" }
}
}
function search(obj,str){
// remove space from str
str = str.replace(/\s/g,'');
var params = str.split('and');
var res = [];
for(item in obj){
if(obj.hasOwnProperty(item) && obj[item].color == params[0] && obj[item].size == params[1]
){
res.push(obj[item]);
}
}
// return the first item id or empty string if not found
// can do something like this :
return (res.length)?res[0].v_id:'';
}
console.log(search(product_1.variants,'gold and 25|25')); // output: 394
答案 2 :(得分:0)
function getVariantId(prodObj, searchFor) {
//i.e. var searchFor = "gold and 20|50"
var cond = searchFor.split(' and ')
for(key in prodObj.variants) {
if (prodObj.variants[key].color === cond[0] && prodObj.variants[key].size === cond[1]) return key
}
}