如何根据另一个值获取对象中的值

时间:2020-12-28 14:47:31

标签: javascript for-loop object

我可以使用一些帮助来循环浏览一个对象并获得两种产品之间的价格差异。比如大锤子和小锤子的价格差多少?

这是我目前所拥有的

var myarray = [{product: "big hammer", price: 32},{product: "small hammer", price: 22},{product: "wrench", price: 15},{product: "saw", price: 55}];

getPriceDifference(myarray[0].product);


function getPriceDifference(currentProduct){

   if(currentProduct === "Big Hammer"){

     //do something...this is where I am stuck

   }



}

提前致谢。

2 个答案:

答案 0 :(得分:1)

有多种迭代数组的方法

myarray.map(item => {

})
myarray.foreach(item => {

})

或者,如果您将数据结构更改为以下内容,则不必进行迭代。

var products = {
  "big hammer": { price: 32 },
  "small hammer": { price: 22 },
  "wrench": { price: 15 },
  "saw": { price: 55 },
};

function getPriceDifference(product_1, product_2) {
  return Math.abs(products[product_1].price - products[product_2].price);
}

var difference = getPriceDifference("big hammer", "small hammer");
console.log(difference);

答案 1 :(得分:0)

这有效:

var myarray = [{product: "big hammer", price: 32},{product: "small hammer", price: 22},{product: "wrench", price: 15},{product: "saw", price: 55}];

function getPriceDifference(first, second){

   for(var i = 0; i < myarray.length; i++){

   if(myarray[i]['product'] == first) price_first = myarray[i]['price'];
   if(myarray[i]['product'] == second) price_second = myarray[i]['price'];

   }

   return Math.abs(price_first - price_second);
}

console.log(getPriceDifference('small hammer', 'big hammer'));