簡體   English   中英

返回具有最小屬性值的 object 鍵

[英]Return object key with minimum property value

我有一個帶有多個鍵的 object(例如 idOne、idTwo、idThree、idFour)...每個鍵都包含一個對象數組。 我想以最低價格退回 output 鑰匙 在此示例中,idThree 包含 id 的最低價格,因此應為 output idThree。 我有返回找到的最低價格的代碼......但我的目標是返回密鑰(idThree)。 有沒有更簡單/更清潔的方法?

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

當前代碼

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?

如果您首先將 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);

要訪問數組的屬性,請使用[index]其中index是您要訪問的索引:

const key = minEntry[0]

您可以使用嵌套的 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)

使用 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 )

使用步驟的簡單方法

  1. 創建sumPrices() function 以獲取價格總和。
function sumPrices(arr){
    sum = 0;
    for(const price of arr){
        sum += price["price"]
    }
    return sum;
}
  1. 創建變量keys具有所有鍵。 創建兩個變量minKey最低價格的關鍵。 minSum最低價格的總和。
const keys = Object.keys(object);
let minKey = null,
    minSum = Number.MAX_SAFE_INTEGER;
  1. 遍歷數組鍵獲取每個內部數組的每個總和,如果小於最小值,則將currentSumminSum進行比較。 用他們的接收鍵跟蹤 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