[英]Javascript ES5: How to Group By a key and create Sub objects from a flat array of key-value objects without using Lodash or Underscore
[英]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.