0

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.

3 Answers 3

1
const newData = data.map(user => ({ _id: user._id, name: { en: user.name } }))
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, so when i have an object with 20 properties, i have to write down like this ? { _id: user._id, name: { en: user.name }, ..... } where .... is the others properties ?
yeah, just append them, though if you really have 20 props and want to copy all of them, just do {...user, newProp: 'newValue'}, (there 3 dots are part of the code)
Hi, your solution is working but when append like you said {..., newProp:"newValue"} output elements has new properties like : '$__': InternalCache { strictMode: true, selected: {}, shardval: undefined, .... Why?
const d = newData.map( (item) => { return {...item, name:{en:"test"}} } )
0

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

Comments

0

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.

2 Comments

Thank you, consider there is 20 properties, how to avoid to write them all?
@ikalangita its depends if you have to reformat them like "name" property. if they have no change, you can change the return to: return { ...obj, _id: obj._id, name: { en: obj.name } }, updated my answer