1

How can I transform values from an array to a new array?

I have an array like:

[
  { "amount" : 10, "date" : "2017-05-30" }...
]

which I want to "transform" into

[
  { x : 10, y: 2017-05-30 }
]

any help is appreciated...

ST80
  • 3,565
  • 16
  • 64
  • 124
  • Do you just want to change the names of the object keys? – PeterMader May 30 '17 at 13:02
  • @PeterMader basically yes :-) – ST80 May 30 '17 at 13:02
  • 1
    I wonder why normal posting rules never apply when people can answer full code in less than 30 seconds... does the easy rep take priority over the quality of the question... even the question now has 2 upvotes (which I assume is to attract attention to the answers)... where are the comments asking for the OP to show what they have tried?? Not to mention the duplicates! – musefan May 30 '17 at 13:04

3 Answers3

7

You could map new objects with the new properties.

var array = [{ amount: 10, date: "2017-05-30" }],
    newArray = array.map(a => ({ x: a.amount, y: a.date }));

console.log(newArray);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

Using Array#map()

The callback function will create a new object with the 2 properties needed. You just have to keep the value of the current array

const array = [{ "amount" : 10, "date" : "2017-05-30" }];

let newArray = array.map(_=>({x:_.amount,y:_.date}));
console.log(newArray);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

You can try using lodash map Lodash map

It will be something like:

const array2 = _.map(array1, (item) => { x: item.amount, y: item.date });
gpanagopoulos
  • 2,842
  • 2
  • 24
  • 19