Chris
Chris

Reputation: 185

Reformat array in react

Using react I'm looking for a way to transform this Json

[
   {
      "date":"2019-01-01",
      "a":4000,
      "f":251,
      "h":0.15,
   },
   {
      "date":"2019-01-02",
      "a":878,
      "f":987,
      "h":0.87,
   },
   {
      "date":"2019-01-03",
      "a":1287,
      "f":412,
      "h":0.56,
   }
]

Into something like this :

{
    date: [
        '2019-01-01',
        '2019-01-02',
        '2019-01-03'
    ],
    a: [
        4000,
        878,
        1287
    ]
};

But using Array.forEach, It doesn't works because I can't create named keys.

So far here's what I have (tempData is the Json I receive):

let newData = [];
tempData.forEach((element,i) => {
    newData['date'][i] = element.date;
    newData['a'][i] = element.i;
});

I can't figure out how to make a new array like I want

Upvotes: 2

Views: 1230

Answers (2)

Andrew
Andrew

Reputation: 28539

That is because you have specified newData as an array but you are looking to use it like an object. Also there are no keys with arrays defined in the object, so you need to define them first of all before trying to insert into them.

If you change you declaration to

let newData = { data: [], a: [] }

also you need to fix the line

newData['a'][i] = element.i;

it should be

newData['a'][i] = element.a;

it should work.

let tempData = [
  {
    "date":"2019-01-01",
    "a":4000,
    "f":251,
    "h":0.15,
  },
  {
    "date":"2019-01-02",
    "a":878,
    "f":987,
    "h":0.87,
  },
  {
    "date":"2019-01-03",
    "a":1287,
    "f":412,
    "h":0.56,
  }
];

let newData = { date: [], a: []};
tempData.forEach((element,i) => {
    newData['date'][i] = element.date;
    newData['a'][i] = element.a;
});

console.log(newData)

If you want you can also dynamically create the keys in the object, something similar to this.

let tempData = [
  {
    "date":"2019-01-01",
    "a":4000,
    "f":251,
    "h":0.15,
  },
  {
    "date":"2019-01-02",
    "a":878,
    "f":987,
    "h":0.87,
  },
  {
    "date":"2019-01-03",
    "a":1287,
    "f":412,
    "h":0.56,
  }
];

let newData = { };
let keys = Object.keys(tempData[0])
keys.forEach(key => {
  newData[key] = []
})

tempData.forEach((element,i) => {
    Object.keys(element).forEach( key => {
      newData[key].push(element[key])
    })
});

console.log(newData)

Upvotes: 2

Elethier
Elethier

Reputation: 95

You don't actually need React for this. You should be able to do this with plain JavaScript. The map method on the Array object will help. Here's one way to do it:

let newData = {};
let dates = newData.map(data => data.date); // "dates" is now an array
let aValues = newData.map(data => data.a); // "aValues" is now an array
newData.date = dates;
newDate.a = aValues;

Hope this helps!

Upvotes: 0

Related Questions