简体   繁体   中英

Update an object with map ( inline es6 )

I have this code , it's work

series.map( el => {
                if ( !el.label ) {
                    el.label = getTranslation(messages, 'label.unstranslated')
                }
            })

But if i do that it's not work

         series.map( el => {
                       const obj {...el,label: el.label ? el.label :  getTranslation(messages, 'label.unstranslated')}
                      return obj
        })

Obj is updated but series not

Finally I want like this form

series.map( el => ({...el,label: el.label ? el.label :  getTranslation(messages,'label.unstranslated')})

but it didn't work

.map()返回新数组,因此您需要将其分配给series

var mappedSeries = series.map( el => ({...el,label: el.label || getTranslation(messages,'label.unstranslated')})

What map does it to iterate an array, do something, and return a new array with the items that you returned in the callback.

On your first example, you are altering the objects as you iterate them, and because this is a reference, your items do get altered. On the lines below el is a reference to the object been iterated. For something like that, you should consider using forEach instead of map.

 if ( !el.label ) {
     el.label = getTranslation(messages, 'label.unstranslated')
  }

On your 2nd example, you are returning a new object, as you should to work properly with the map function, but you are not assigning it to anything, and the items dont get altered because now you are not tampering with the el , you just read its values in to a new object, like you should. So just assign the result to a new variable to test it.

   var mapedSeries=  series.map( el => {
           const obj {...el,label: el.label ? el.label :  getTranslation(messages, 'label.unstranslated')}
           return obj;
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM