I have the data like the below from API.I want to format the data. can anyone will help?
fields: [
{
name: "A",
values: {
data: [1, 2, 3, 4, 5]
}
},
{
name: "B",
values: {
data: [6, 7, 8, 9, 10]
}
}
]
how to get the output like this
var d = [[1,6],[2,7],[3,8],[4,9],[5,10]]
>Solution :
If you have the same array index and everything is static and not dynamic except the values, you can do something like this:
const obj = {
fields: [
{
name: "A",
values: {
data: [1, 2, 3, 4, 5]
}
},
{
name: "B",
values: {
data: [6, 7, 8, 9, 10]
}
}
]
};
let out;
if (obj.fields[0].values.data.length === obj.fields[1].values.data.length) {
const [d1, d2] = [obj.fields[0].values.data, obj.fields[1].values.data];
out = d1.map((v, i) => [v, d2[i]]);
}
console.log(out);
Assumptions:
- I used
objas the object that stores the response. - The structure is always
fields[X].values.data. - There are only two indices:
fields[0].values.dataandfields[1].values.data.
Output
[ [1, 6], [2, 7], [3, 8], [4, 9], [5, 10] ]