user3137766
user3137766

Reputation:

Change an object value inside a loop in JavaScript

I have an array of objects like this:

const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]

I have to change each item name property to something like this :

...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}

My attempt is to loop object like following :

data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})

But this always console the original item and the name property value is not modified.

Upvotes: 0

Views: 77

Answers (3)

Guy Cohen
Guy Cohen

Reputation: 194

try somthing like:

const newList = data.map(obj => {
return { _id: obj._id, name: { en: obj.name } }
});

and the newList list is your new data list so you can do it:

data = newList;

EDIT:

if you have more properties you can change the return line to:

return { ...obj, name: { en: obj.name } }

what will happen here, it will deploy all the object properties as they are, and modify the name property, unfortunately, every property you want to modify, you have to re-write it.

Upvotes: 0

richytong
richytong

Reputation: 2452

I created a library to express transformations like this very simply.

const { pipe, fork, get } = require('rubico')

const data = 
    [ { _id: '49847444033', name: 'yoko'} 
    , { _id: '49847433333', name: 'doira'} 
    ]

const onData = pipe([
  fork({
    _id: get('_id'), // data => data._id
    name: fork({ en: get('name') }), // data => ({ en: data.name })
  }),
  console.log,
])

data.map(onData) /*
{ _id: '49847444033', name: { en: 'yoko' } }
{ _id: '49847433333', name: { en: 'doira' } }
*/

I've commented the code above, but to really understand rubico and get started using it, I recommend you read the intuition and then the docs

Upvotes: 0

DedaDev
DedaDev

Reputation: 5249

const newData = data.map(user => ({ _id: user._id, name: { en: user.name } }))

Upvotes: 1

Related Questions