Search code examples
javascriptlodash

Lodash fp replace in an object's property


I try to run this code for replace some string in an object's property with loadsh.

var data = [
   { name: 'test1', value: 'foo - bar' },
   { name: 'test2', value: 'foo - bar' },
   { name: 'test3', value: 'foo - bar' }
]

var newData = fp.compose(
  fp.map('value'),
  fp.replace('/-/gm', '')
)(data)

console.log(newData)
//display : [ undefined,
     undefined,
     undefined,
     undefined,
     ....
   ]

but I want :

[
  { name: 'test1', value: 'foo  bar' },
  { name: 'test2', value: 'foo  bar' },
  { name: 'test3', value: 'foo  bar' }
]

Thank you for your help.


Solution

  • You are extracting an array of the value property values, and then you try to replace the array (not the items) using a regex. You need to _.map() the array, and perform the replace on each element, using the callback:

    var data = [
       { name: 'test1', value: 'foo - bar' },
       { name: 'test2', value: 'foo - bar' },
       { name: 'test3', value: 'foo - bar' }
    ]
    
    var newData = _.map(({ value, ...rest }) => ({
      ...rest,
      value: _.replace(/\s-\s/gm, ' ', value)
    }))(data)
    
    console.log(newData);
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>