這個問題在這里已經有了答案: 比較 JavaScript 中的物件陣列 17 個答案 比較兩個物件陣列,如果物件值相等則洗掉 2 個答案 比較與順序無關的物件陣列 3 個答案 1 小時前關閉。
我有兩個陣列。一是模式,包含 12 個月,二是從 api 獲取。圖案:
[
{
total: 0,
month_name: "Jan",
},
{
total: 0,
month_name: "Feb",
},
{
total: 0,
month_name: "Mar",
},
{
total: 0,
month_name: "Apr",
},
...
]
獲取:
[
{
"total": 4,
"month_name": "Mar"
},
{
"total": 1,
"month_name": "Apr"
}
]
我想將獲取的陣列與模式進行比較,找到匹配的“month_name”并更新“total”。獲取的陣列僅包含大于 0 的月份的物件。
uj5u.com熱心網友回復:
我建議制作一個查找表 ( totalByMonth),然后您可以遍歷state并通過查找totalin來更新每個表totalByMonth。
const state = [
{total: 0, month_name: "Jan"},
{total: 0, month_name: "Feb"},
{total: 0, month_name: "Mar"},
{total: 0, month_name: "Apr"}
];
const fetched = [
{total: 4, month_name: "Mar"},
{total: 1, month_name: "Apr"}
];
//build totalByMonth object
const totalByMonth = {};
for (let f of fetched) {
totalByMonth[f.month_name] = f.total;
}
//update state
for (let s of state) {
const total = totalByMonth[s.month_name];
if (total) s.total = total;
}
console.log(state);
uj5u.com熱心網友回復:
你可以試試這個:
let result = months.map(month => {
let matching_result = fetched.filter(f => f.month_name == month.month_name);
return matching_result[0] ? {...month, total: matching_result[0].total}: month;
});
console.log(result);
//Output
// [
// {total: 0, month_name: 'Jan'},
// {total: 0, month_name: 'Feb'},
// {total: 4, month_name: 'Mar'},
// {total: 1, month_name: 'Apr'},
// ]
uj5u.com熱心網友回復:
let pattern=[{total:0,month_name:"Jan"},{total:0,month_name:"Feb"},{total:0,month_name:"Mar"},{total:0,month_name:"Apr"}]
let fetched=[{total:4,month_name:"Mar"},{total:1,month_name:"Apr"}];
function updateTotal(pattern,fetched){
fetched.forEach((e) => {
let index = pattern.findIndex(p => p.month_name === e.month_name)
if(index > -1){
pattern[index].total = e.total
}
} )
}
updateTotal(pattern,fetched)
console.log(pattern)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494821.html
標籤:javascript 数组 api 排序
