简体   繁体   中英

How to add value of missing object after comparing to another array?

I have an array of months ( var months ), and I am trying to filter out and get the months that the array of object ( var array1 ) does not have and add empty value of property Avg

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20},
{Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}];`

Eg. array1 has the property value of Month: Jan , Feb , May and Jun , but I want to get the months that are missing and add value of 0 to property Avg like {Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, ... for the missing months comparing it with months array

Expected result of array1:

[{Month: 'Jan', Avg: 10}, {Month: 'Feb', Avg: 20}, 
{Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, 
{Month: 'May', Avg: 50}, {Month: 'Jun', Avg: 60}, 
{Month: 'Jul', Avg: 0}, {Month: 'Aug', Avg: 0},
{Month: 'Sep', Avg: 0}, {Month: 'Oct', Avg: 0}, 
{Month: 'Nov', Avg: 0}, {Month: 'Dec', Avg: 0}];

Use Array.map with Array.find

 const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20}, {Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}]; const result = months.map(m => array1.find(a => a.Month === m)??{Month: m, Avg: 0}); console.log(result);

Reference: Array , Nullish

I think this should work pretty much!

 var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; var array1 = [{ Month: "Jan", Avg: 10 }, { Month: "Feb", Avg: 20 }, { Month: "May", Avg: 50 }, { Month: "Jun", Avg: 60 }, ]; let finalArr = []; months.filter((e) => { let index = array1.findIndex((ele) => ele.Month == e); if (index >= 0) { finalArr.push(array1[index]); } else { finalArr.push({ Month: e, Avg: 0 }); } }); console.log(finalArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM