I have two arrays. One is the pattern, which contains 12 months and second is fetched from api. Pattern:
[
{
total: 0,
month_name: "Jan",
},
{
total: 0,
month_name: "Feb",
},
{
total: 0,
month_name: "Mar",
},
{
total: 0,
month_name: "Apr",
},
...
]
fetched:
[
{
"total": 4,
"month_name": "Mar"
},
{
"total": 1,
"month_name": "Apr"
}
]
I want to compare fetched array to pattern, find matching "month_name" and update "total". Fetched array contains objects with months only when they are above 0.
I'd suggest making a lookup table (totalByMonth) then you can just loop over the state and update each one by looking up the total in 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);
You can try this :
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'},
// ]
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)