javascript 使用 lodash 在数组中替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19860039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:02:58  来源:igfitidea点击:

Replace in array using lodash

javascriptunderscore.jslodash

提问by Andreas K?berle

Is there an easy way to replace all appearances of an primitive in an array with another one. So that ['a', 'b', 'a', 'c']would become ['x', 'b', 'x', 'c']when replacing awith x. I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.

有没有一种简单的方法可以用另一个替换数组中一个基元的所有外观。所以这['a', 'b', 'a', 'c']将成为['x', 'b', 'x', 'c']更换时ax。我知道这可以通过 map 函数来完成,但我想知道是否忽略了一种更简单的方法。

回答by Benjamin Gruenbaum

In the specificcase of strings your example has, you can do it natively with:

在您的示例具有的字符串的特定情况下,您可以使用本机进行:

myArr.join(",").replace(/a/g,"x").split(",");

Where "," is some string that doesn't appear in the array.

其中“,”是一些未出现在数组中的字符串。

That said, I don't see the issue with a _.map- it sounds like the better approach since this is in fact what you're doing. You're mapping the array to itself with the value replaced.

也就是说,我没有看到 a 的问题_.map- 这听起来是更好的方法,因为这实际上是您正在做的。您将数组映射到自身并替换了值。

_.map(myArr,function(el){
     return (el==='a') ? 'x' : el;
})

回答by Tomalak

I don't know about "simpler", but you can make it reusable

我不知道“更简单”,但你可以让它可重用

function swap(ref, replacement, input) {
    return (ref === input) ? replacement : input;
}

var a = ['a', 'b', 'a', 'c'];

_.map(a, _.partial(swap, 'a', 'x'));

回答by j1s

If the array contains mutable objects, Its a straight forward with lodash find function.

如果数组包含可变对象,则可以直接使用 lodash find 函数。

var arr = [{'a':'a'}, {'b':'b'},{'a':'a'},{'c':'c'}];    

while(_.find(arr, {'a':'a'})){
  (_.find(arr, {'a':'a'})).a = 'x';
}

console.log(arr); // [{'a':'x'}, {'b':'b'},{'a':'x'},{'c':'c'}]

回答by Ihor

Another simple solution. Works well with arrays of strings, replaces all the occurrences, reads well.

另一个简单的解决方案。适用于字符串数组,替换所有出现的,读取良好。

var arr1 = ['a', 'b', 'a', 'c'];
var arr2 = _.map(arr1, _.partial(_.replace, _, 'a', 'd'));
console.log(arr2); // ["d", "b", "d", "c"]