简体   繁体   English

返回具有最小属性值的 object 键

[英]Return object key with minimum property value

I have an object with multiple keys (eg idOne, idTwo, idThree, idFour)... each key contains an array of objects.我有一个带有多个键的 object(例如 idOne、idTwo、idThree、idFour)...每个键都包含一个对象数组。 I would like to return and output the key with minimum price .我想以最低价格退回 output 钥匙 In this example, idThree contains the minimum price of id and therefore should output idThree.在此示例中,idThree 包含 id 的最低价格,因此应为 output idThree。 I have code that returns the minimum price found... but my goal is to return key (idThree).我有返回找到的最低价格的代码......但我的目标是返回密钥(idThree)。 Is there a simpler/cleaner way?有没有更简单/更清洁的方法?

const object = {
   idOne: [{ price: 300 }],
   idTwo: [{ price: 200 }, { price: 100 }],
   idThree: [{ price: 90 }, { price: 100 }],
   idFour: [{ price: 99 }, { price: 210 }]
}

Current Code当前代码

const arrayOfMinValues = []
for (const [key, value] of Object.entries(object)) {
  const minimumEntry = Math.min(...value.map(item => item.price))
  arrayOfMinValues.push(minimumEntry)
}

console.log('MIN VALUE IS: ', Math.min(...arrayOfMinValues)) // how can I return key?

If you first turn the object into an array of entries, and turn each subarray into the single lowest price in the array, you can then .reduce to iterate over all of those lowest prices and pick out the entry with the lowest one:如果您首先将 object 转换为条目数组,并将每个子数组转换为数组中的单个最低价格,然后您可以.reduce遍历所有这些最低价格并挑选出最低价格的条目:

 const object = { idOne: [{ price: 300 }], idTwo: [{ price: 200 }, { price: 100 }], idThree: [{ price: 90 }, { price: 100 }], idFour: [{ price: 99 }, { price: 210 }] } const minEntry = Object.entries(object).map(([key, arr]) => [key, Math.min(...arr.map(obj => obj.price))]).reduce((a, b) => a[1] > b[1]? b: a); console.log('Min entry:', minEntry);

To access a property of an array, use [index] where index is the index you want to access:要访问数组的属性,请使用[index]其中index是您要访问的索引:

const key = minEntry[0]

You can use nested reduce calls to get an object with the minimum key and value , and destructure the key :您可以使用嵌套的 reduce 调用来获取具有最小keyvalue的 object ,并解构key

 const object = {"idOne":[{"price":300}],"idTwo":[{"price":200},{"price":100}],"idThree":[{"price":90},{"price":100}],"idFour":[{"price":99},{"price":210}]} const { key } = Object.entries(object).reduce((acc, [key, values]) => values.reduce((r, { price }) => price < r.price? { key, price }: r, acc), { key: null, price: Infinity }) console.log(key)

Another variation of reduce() using find()使用 find() 的 reduce() 的另一种变体

 const object = {"idOne":[{"price":300}],"idTwo":[{"price":200},{"price":100}],"idThree":[{"price":90},{"price":100}],"idFour":[{"price":99},{"price":210}]} const [key, lp] = Object.entries(object).reduce((a, [k, v])=>{ const low = v.find(o => o.price < a[1]); return low? [k, low.price]: a; },[null,Infinity]) console.log(key, ' has low price of ',lp )

Simple approach to use with steps:使用步骤的简单方法

  1. Create sumPrices() function to get sum of prices.创建sumPrices() function 以获取价格总和。
function sumPrices(arr){
    sum = 0;
    for(const price of arr){
        sum += price["price"]
    }
    return sum;
}
  1. Create variable keys has all keys.创建变量keys具有所有键。 Create two vars minKey the key of lowest prices.创建两个变量minKey最低价格的关键。 and minSum sum of lowest prices.minSum最低价格的总和。
const keys = Object.keys(object);
let minKey = null,
    minSum = Number.MAX_SAFE_INTEGER;
  1. iterate over array keys get each sum of each inner array and compare currentSum with minSum if less than minimum.遍历数组键获取每个内部数组的每个总和,如果小于最小值,则将currentSumminSum进行比较。 keep track the minSum with thier recpective key.用他们的接收键跟踪 minSum。
for(const key of keys){
    const currentSum = sumPrices(object[key])
    if(currentSum <= minSum){
          minKey = key;
          minSum = currentSum;
    }
}
console.log(minKey);

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

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