Search code examples
javascriptobjectecmascript-6ecmascript-5

Javascript update Object attribute value


I´m trying to update the object atribute:

   data : [
     {"id":1,"rp":"2426","cr":"11-11"},
     {"id":1,"rp":"1119","cr":"19-21"},
     {"id":1,"rp":"3453","cr":"23-81"}
    ]

new object would be updated as below.

NewData: [
 {"id":1,"rp":"2426","cr":"11/11"},
 {"id":1,"rp":"1119","cr":"19/21"},
 {"id":1,"rp":"3453","cr":"23/81"}
]

I looking to update the object cr atribute for all values, for example using javascript.replace() method, I would do replace("-","/").


Solution

  • You could use map method to create new array and replace to update cr property.

    var data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
    var update = data.map(({cr, ...rest}) => ({...rest, cr: cr.replace("-","/")}))
    console.log(update)