简体   繁体   English

Lodash fp替换对象的属性

[英]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. 我尝试运行此代码,用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. 谢谢您的帮助。

You are extracting an array of the value property values, and then you try to replace the array (not the items) using a regex. 您正在提取value属性值的数组,然后尝试使用正则表达式替换该数组(而不是项目)。 You need to _.map() the array, and perform the replace on each element, using the callback: 您需要_.map()数组,并使用回调对每个元素执行替换:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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