Search code examples
javascriptecmascript-6ecmascript-2016

ES6: How to go through an array of object and change one of the items in there


I'm trying to divide one item in array of objects by 1000 and return a new version with calculated value

0: {name: "Mon, 28", from: 10236, to: -0, time: "2019-01-28T18:51:04+01:00"}
1: {name: "Tue, 29", from: 10209, to: -0, time: "2019-01-29T18:51:03+01:00"}
2: {name: "Wed, 30", from: 12088, to: -0, time: "2019-01-30T18:51:01+01:00"}
3: {name: "Thu, 31", from: 10789, to: -0, time: "2019-01-31T18:50:59+01:00"}
4: {name: "Fri, 1", from: 11449, to: -0, time: "2019-02-01T18:50:56+01:00"}
5: {name: "Sat, 2", from: 13404, to: -0, time: "2019-02-02T18:50:48+01:00"}

const data2 = data.map(entry => {
        let rObj = {}
        rObj[entry.key] = entry.name
        rObj[entry.from] = entry.from / 1000
        rObj[entry.to] = entry.to
        rObj[entry.time] = entry.time
        return rObj
        // return entry.from
    })

I expect the result be like

0: {name: "Mon, 28", from: 10.236, to: -0, time: "2019-01-28T18:51:04+01:00"}
1: {name: "Tue, 29", from: 10.209, to: -0, time: "2019-01-29T18:51:03+01:00"}
2: {name: "Wed, 30", from: 12.088, to: -0, time: "2019-01-30T18:51:01+01:00"}
3: {name: "Thu, 31", from: 10.789, to: -0, time: "2019-01-31T18:50:59+01:00"}
4: {name: "Fri, 1", from: 11.449, to: -0, time: "2019-02-01T18:50:56+01:00"}
5: {name: "Sat, 2", from: 13.404, to: -0, time: "2019-02-02T18:50:48+01:00"}

any help would be appreciated.


Solution

  • You can achieve this using map() method of arrays. If you using 0,1,2... as keys i would suggest you to use array instead. Below is example with array

    const arr = [{name: "Mon, 28", from: 10236, to: -0, time: "2019-01-28T18:51:04+01:00"},
    {name: "Tue, 29", from: 10.209, to: -0, time: "2019-01-29T18:51:03+01:00"},
    {name: "Wed, 30", from: 12.088, to: -0, time: "2019-01-30T18:51:01+01:00"},
    {name: "Thu, 31", from: 10.789, to: -0, time: "2019-01-31T18:50:59+01:00"},
    {name: "Fri, 1", from: 11.449, to: -0, time: "2019-02-01T18:50:56+01:00"},
    {name: "Sat, 2", from: 13.404, to: -0, time: "2019-02-02T18:50:48+01:00"}]
    
    const newArr = arr.map(item => ({...item,from:item.from/1000}))
    console.log(newArr)