Javascript 如何在阵列中使用reduce tp筛选器项?
我有这个数组,我正在使用filter和forEach函数(它工作得很好),但我想使用reducejavascript函数。提前多谢了 下面是使用过滤器和forEach的解决方案Javascript 如何在阵列中使用reduce tp筛选器项?,javascript,Javascript,我有这个数组,我正在使用filter和forEach函数(它工作得很好),但我想使用reducejavascript函数。提前多谢了 下面是使用过滤器和forEach的解决方案 arr .filter(el => typeof el.value === 'string' && el.value.includes('test')) .forEach(el => { if (el.key === 'cars') {
arr
.filter(el => typeof el.value === 'string' && el.value.includes('test'))
.forEach(el => {
if (el.key === 'cars') {
el.value = el.value.replace('test', 'TICO');
}
}
);
也许是这样:
arr.reduce((all, el) => {
if ((el) => typeof el.value === 'string' && el.value.includes('test'))
all.push({
...el,
value: el.key === 'cars' ? el.value.replace('test', 'TICO') : el.value,
});
return all;
}, []);
这将使用
数组来播放相同的函数。reduce
const result=arr.reduce((acc,el)=>{
if(type of el.value==='string'&&el.value.includes('test')){
加速推({
…呃,
值:el.key==='cars'?el.value.replace('test','TICO'):el.value
});
}
返回acc;
}, []);
控制台日志(结果)代码>
但是您不需要过滤器()
。您当前(ab)正在使用过滤器,这只是forEach
内部过滤器的另一个条件。您也可以在forEach
你甚至可以继续做下去
arr.forEach(el => {
if (typeof el.value === 'string' && el.key === 'cars') {
el.value = el.value.replace('test', 'TICO');
}
});
我甚至不认为这会降低性能,因为replace
必须“找到”字符串test
。您想做什么?您的预期输出是什么?@Yousaf如果我尝试做同样的事情,但是使用“reduce”javascript函数,确实我不认为您想要减少数组,而且forEach
不会做任何事情,我认为您想要在过滤数组之后映射
方法,当.filter()
和.map()
方法更适合执行您正在执行的操作时,我希望使用reduce javascript函数执行此操作
但是为什么reduce
对于您正在做的事情来说是错误的工具,那么您为什么坚持使用它呢?为什么reduce
而不是some
例如?在push
部分中,它应该是…all
而不是…el
。无论如何,我认为他/她不想使用reduce
而不仅仅是过滤器
和地图
@agustimoles它应该是…el
,不是…all
,因为all
是整体array@AgustinMoles实际上应该是…el
,因为如果键是cars
@losif,我们想用更改的值推送元素,谢谢您输入兄弟@progx没问题非常感谢你的帮助兄弟!谢谢你的输入兄弟!
arr.forEach(el => {
if (typeof el.value === 'string' && el.key === 'cars') {
el.value = el.value.replace('test', 'TICO');
}
});