我有一大堆物件,我試圖合并到我有一個物件陣列的地方,如下所示:每個專案(例如:香蕉)將在 2 個單獨的物件中,因為我正在嘗試匯總所有購買訂單和銷售訂單,這些是不同的價格/資料。
我試過抓取獨特的配對(香蕉、蘋果、橙子等)并通過它和另一個資料地圖進行映射,但我無法弄清楚。
let uniquePairing = Array.from([...new Set(data.map(item => item["name"]))])
**let data = [{
name:'banana,
price:( average cost)
type:buy
items: ( total bananas)
fee: ( total fees)
},
{
name:'banana,
price:( average cost)
type:sell
items: ( total bananas)
fee: ( total fees)
},
{ apples...
]**
資料示例
let data = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy"
fee: 0.5
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]
uj5u.com熱心網友回復:
如果我正確理解您的問題,您可以使用該reduce功能:
let uniquePairing = data.reduce((total, currentObj) => {
const name = currentObj.name,
type = currentObj.type;
// Group by both `type` and `name`
let relatedObj = total.find(obj => obj.name === name && obj.type === type);
if (!relatedObj) {
total.push({
...currentObj,
// Adding `totalPrice` and `objCount` to track the cost average
totalPrice: currentObj.price,
objCount: 1
})
} else {
relatedObj.totalPrice = currentObj.price;
relatedObj.objCount ;
relatedObj.price = relatedObj.totalPrice / relatedObj.objCount;
relatedObj.items = currentObj.items;
relatedObj.fee = currentObj.fee;
}
return total;
}, []);
uj5u.com熱心網友回復:
你可以這樣做:
let data = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]
const getFruitData = (fruits, fruit) => fruits.filter(fr=> fr.name===fruit.name && fr.type=== fruit.type)
const getTotal = (fruits, field) => fruits.reduce((acc,cur)=> acc =cur[field], 0)
const isRegistered = (fruits, value) => fruits.some(fruit=> fruit.type === value.type && fruit.name===value.name)
const getFruits = (fruits) => {
return fruits.reduce((acc, cur)=> {
if(isRegistered(acc, cur)){
return acc
}
acc.push({name: cur.name, type: cur.type})
return acc
}, [])
}
function mergeData(arr){
const fruits = getFruits(arr)
return fruits.map(fruit=> {
const data = getFruitData(arr, fruit)
return {
name: fruit.name,
price: getTotal(data, "price"),
type: fruit.type,
fee: getTotal(data, "fee"),
items: getTotal(data, "items")
}
})
}
console.log(mergeData(data))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400031.html
標籤:javascript
上一篇:如何更改jsx檔案的背景影像
下一篇:如何使用DiscordAPI使`CommandInteraction.reply()`回傳一個`Message`
