[英]JavaScript combines multiple arrays based on data
When type equals all, I need to combine two arrays into one.当类型等于全部时,我需要将两个数组合二为一。 I have the code, but it gets the wrong result。
我有代码,但得到了错误的结果。
const arr = [{value: 'aa'}, {value: 'bb'}]; const arr2 = [{type: 'all'}, {type: 'text', value: 'a2'}, {type: 'all'}] arr.forEach((item, index) => { arr2.forEach((items, indexs) => { if (items.type === 'all') { items.value = arr[index].value } }) }) console.log(arr2)
I hope to get this result我希望得到这个结果
arr2 = [{type: 'all', value: 'aa'}, {type: 'text', value: 'a2'}, {type: 'all', value: 'bb'}] console.log(arr2)
It's not a good idea to mutate the data that you're looping over.改变您正在循环的数据并不是一个好主意。
If I understand correctly, you need to iterate through arr2
and intersperse items from arr
when type is all
.如果我理解正确,当 type 为
all
时,您需要遍历arr2
并散布来自arr
项目。
I'd use Array.map
for this sort of thing:我会使用
Array.map
来处理这种事情:
const arr = [{value: 'aa'}, {value: 'bb'}]; const arr2 = [{type: 'all'}, {type: 'text', value: 'a2'}, {type: 'all'}] const combined = arr2.map(({type, ...rest})=>type==='all'?{type, ...arr.shift()}:{type, ...rest}) console.log(combined)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.