简体   繁体   English

如何根据另一个值在 object 中获取值

[英]How to get value in object based on another value

I could use some help cycling through an object and getting the difference in price between two products.我可以通过 object 使用一些帮助,并获得两种产品之间的价格差异。 For example, what is the difference in price between the big hammer and the small hammer?比如大锤子和小锤子的价格有什么区别?

Here's what I have so far这是我到目前为止所拥有的

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

   }



}

Thanks in advance.提前致谢。

There are multiple ways of iterating over arrays有多种方法可以迭代 arrays

myarray.map(item => {

})
myarray.foreach(item => {

})

Or if you change the structure of your data to the following, you do not have to iterate.或者,如果您将数据结构更改为以下内容,则不必进行迭代。

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);

This works:这有效:

 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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM