簡體   English   中英

使用Lodash或Underscore JS,如何基於同一對象數組中的另一個鍵值獲取特定的鍵值

[英]Using Lodash or Underscore JS , how do I obtain a specific key value based on another key value within the same objects array

這是我正在使用的數據:

   myData = 
    [ { sn: '103261101',
        status: 1,
        qty: '189'
      },
      { sn: '106009801',
        status: 1,
        qty: '12'
      }
    ];

我正在遍歷另一個數據數組,我想將正確的數量與我也在推送數據的新數組相關聯。 它需要針對sn查找數據。

product.push({
  'identifier' :  dataJSON.msg[z].sku,
  'size' : dataJSON.msg[z].size,
  'quantity' : <Here is where I want to do a lodash / underscore find statement> 
});

例如,Easy 1-liner查看myData並根據匹配的sn存儲數量。 在這種情況下,循環內的dataJSON.msg [z] .sku與將用於myData中的sn值相同。

您可以使用find獲得正確的項目,然后僅獲取該項目的qty屬性。

_.find(myData, (item) => item.sn === dataJSON.msg[z].sku).qty

這是與lodash一起使用的jsfiddle: https ://jsfiddle.net/vzwst9o4/

上面的代碼是此的簡寫:

var matchingItem = _.find(myData, function (item) { 
   item.sn === dataJSON.msg[z].sku
});
matchingItem.qty

它在lodash下划線中應該起作用,因為它們的_.find函數起作用。 您也可以使用Javascript find作為其他答案,但是使用lodash或下划線(最好是在其他操作中使用lodash或下划線的情況)可能會更好,因為這樣可以確保跨瀏覽器的兼容性。

考慮以下具有Array.prototype.find()函數的Ecmascript6解決方案:

product.push({
  'identifier' :  dataJSON.msg[z].sku,
  'size' : dataJSON.msg[z].size,
  'quantity' : ''  // default value, cause we can't refer to the 'identifier' key while initializing the object via literal 
});

var lastPos = product.length - 1;  // the last `product` position
if (o = myData.find((o) => o.sn === product[lastPos].identifier)) {
    product[lastPos].quantity = o.qty;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM