[英]Replace in array using lodash
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 a
with x
.所以当用
x
替换a
时, ['a', 'b', 'a', 'c']
会变成['x', 'b', 'x', 'c']
。 I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.我知道这可以通过 map 函数来完成,但我想知道是否忽略了一种更简单的方法。
In the specific case 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.也就是说,我没有看到
_.map
的问题——这听起来是更好的方法,因为这实际上是你正在做的。 You're mapping the array to itself with the value replaced.您将数组映射到自身并替换了值。
_.map(myArr,function(el){
return (el==='a') ? 'x' : el;
})
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'));
If the array contains mutable objects, It's straightforward with lodash's 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'}]
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.