Home > Software design >  How to convert an array from one schema to another in Javascript?
How to convert an array from one schema to another in Javascript?

Time:04-10

I have a JSON array that looks like this:

[{
   "day":"all",
   "client_first":"3",
   "client_second":"2",
   "client_third":"3"
},
{
   "day":"monday",
   "client_first":"2",
   "client_second":"2",
   "client_third":"2"
}]

I would like to transform the above into the following

[{
    label: 'all',
    data: [3,2,3]
},
{
    label: 'monday',
    data: [2,2,2]
}]

Thanks in advance

CodePudding user response:

Given input:

const input = [{
   "day":"all",
   "client_first":"3",
   "client_second":"2",
   "client_third":"3"
},
{
   "day":"monday",
   "client_first":"2",
   "client_second":"2",
   "client_third":"2"
}];

Looks like the semantics of what you want to do align very well with Array.map.

For each values in the input array, map it to an object such that label is set by day (key rename), and put in to data the values of the other entries. To get the entries (key,value pairs) we use Object.entries. We Array.filter to get those with key !== 'day'. We want an array of the values, so we map the filtered entries (key,value pairs) to only the values. The input is string, but looks like you want it as numbers, so we convert using Number function

const output = input.map(obj => ({
    label: obj.day,
    data: Object.entries(obj).filter(([key]) => key !== 'day').map(([, val]) => Number(val)),
}));

CodePudding user response:

In one line of code:
arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})):

let arr = [{
   "day":"all",
   "client_first":"3",
   "client_second":"2",
   "client_third":"3"
},
{
   "day":"monday",
   "client_first":"2",
   "client_second":"2",
   "client_third":"2"
}];
console.log(arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})))

  • Related