如何在对象值调用中使用对象键?

时间:2016-06-15 01:21:55

标签: javascript

所以这可能很简单,但我真的很困惑。

我有以下物品:

Woo: {
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" }
  }
},
product_2: {
  p_id: "212", // Pendant Conicol
  variants: {
    v_1: { v_id:null, color:"gold", size:"20|30" },
    v_2: { v_id:null, color:"gold", size:"20|30" },
    v_3: { v_id:null, color:"gold", size:"20|30" },
    v_4: { v_id:null, color:"gold", size:"20|30" }
  }
},
product_3: {
  p_id: 398, // Standing Conicol
  variants: {
    v_1: { v_id:null, color:"gold", size:"20|30" },
    v_2: { v_id:null, color:"gold", size:"20|30" },
    v_3: { v_id:null, color:"gold", size:"20|30" },
    v_4: { v_id:null, color:"gold", size:"20|30" }
  }
},
product_4: {
  p_id: "212", // Pendant Conicol
  variants: {
    v_1: { v_id:null, color:"gold", size:"20|30" },
    v_2: { v_id:null, color:"gold", size:"20|30" },
    v_3: { v_id:null, color:"gold", size:"20|30" },
    v_4: { v_id:null, color:"gold", size:"20|30" }
  }
}
}

实际代码块:

getVariantId: function() {
  var x = ProductDesigner.Cart.productName;
  var results = Object.keys(ProductDesigner.Woo[x].variants).map(function (key) {
      return ProductDesigner.Woo.product_1.variants[key];
  }).filter(function (object) {
      return object.color === ProductDesigner.Cart.CustomData.Color.innerShade && object.size === ProductDesigner.Cart.CustomData.Size.diameterTop + "|" + ProductDesigner.Cart.CustomData.Size.height;
  });
  ProductDesigner.Cart.v_id = results[0].v_id;
  console.log("Product ID: " + ProductDesigner.Cart.p_id + " Variant ID: " + ProductDesigner.Cart.v_id);
}

1 个答案:

答案 0 :(得分:3)

这是括号表示法的用法。

var aProduct = 'product_1';
console.log(Woo[aProduct].variants); // {v_1: { v_id:397, color:"gold", ..