Home > Mobile >  Merging and Tranforming Array of object in javascripts
Merging and Tranforming Array of object in javascripts

Time:01-09

So i have two array of object like this...

const planned = [
    {
        '2023-01-06': 46,
        '2023-01-04': 45,
        '2023-01-05': 43,
        '2023-01-07': 53
    }
]
const actual =[
    {
        "2023-01-07": 12,
        "2023-01-06": 16,
        "2023-01-04": 14,
        "2023-01-08": 10,
        "2023-01-05": 12,
        "2023-01-03": 10
    }
]

i try to merge it into one array of object that separated the date and the value, here is my expected array:

const transformed =  [{
    date:"2023-01-03",
    actual:10,
    planned:0,
  },{
    date:"2023-01-05",
    actual:10,
    planned:5,
  },{
    date:"2023-01-06",
    actual:16,
    planned:46,
  },....

] here is my try:

const transformed = planned.map((el)=>{
  let obj ={}
  actual.map((els)=>{
     if(el.key === els.key){
       obj["date"]=== el.key
       obj["actual"]=== el.keys
       obj["planned"]=== el.key
     }
  })
 return {...obj}
})

i try to figure it out, but have some issues on how to create the logic... anyone here to give me clue on it? can we use reduce prototype array or any built in?, any help on this will be verry thankful

CodePudding user response:

Here's an approach. planned and actual are arrays, so we first convert them to a flat map and then use this map to create the output

const planned = [
    {
        "2023-01-06": 46,
        "2023-01-04": 45,
        "2023-01-05": 43,
        "2023-01-07": 53,
    },
];
const actual = [
    {
        "2023-01-07": 12,
        "2023-01-06": 16,
        "2023-01-04": 14,
        "2023-01-08": 10,
        "2023-01-05": 12,
        "2023-01-03": 10,
    },
];

const convertToMap = (list) =>
    list.reduce((acc, curr) => ({ ...acc, ...curr }), {});

const actualStats = convertToMap(actual);
const plannedStats = convertToMap(planned);

const dates = [
    ...new Set([...Object.keys(actualStats), ...Object.keys(plannedStats)]),
];

const transformed = dates.map((date) => ({
    date,
    planned: plannedStats[date] || 0,
    actual: actualStats[date] || 0,
}));

console.log(transformed);

  • Related