Tengo dos matrices. Uno es el patrón, que contiene 12 meses y el segundo se obtiene de api. Patrón:
[ { total: 0, month_name: "Jan", }, { total: 0, month_name: "Feb", }, { total: 0, month_name: "Mar", }, { total: 0, month_name: "Apr", }, ... ]obtenido:
[ { "total": 4, "month_name": "Mar" }, { "total": 1, "month_name": "Apr" } ]Quiero comparar la matriz obtenida con el patrón, encontrar el "mes_nombre" coincidente y actualizar el "total". La matriz recuperada contiene objetos con meses solo cuando están por encima de 0.
Sugeriría hacer una tabla de búsqueda ( totalByMonth ), luego puede recorrer el state y actualizar cada uno buscando el total en 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);Puedes probar esto:
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)