简体   繁体   English

JavaScript 根据数据组合多个数组

[英]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.

相关问题 D3:使用多个折线图缩放以某种方式组合它们的数据数组 - D3: Zoom with multiple line charts somehow combines their data arrays JavaScript 基于多个数组过滤对象 - JavaScript filter objects based on multiple arrays 根据长度将字符串拆分为多个数组(javascript) - Splitting a string into multiple arrays based on length (javascript) 使用javascript根据索引合并多个数组 - Merge multiple arrays based on their index using javascript JavaScript - 将对象的多个 arrays 转换为基于水平值的 arrays 数组 - JavaScript - Convert multiple arrays of an objects to horizonal values based array of arrays 使用javascript根据下拉选择填充表中的多个字段,数据应在数组中 - Populating multiple fields in table based on dropdown selection using javascript, the data should be in arrays 如何根据javascript中的多个分隔符将字符串拆分为多个数组 - How to split a string to multiple arrays based on multiple separators in javascript 如何创建结合 Arrays 的算法 - How To Create An Algorithm That Combines Arrays JavaScript、Arrays 中的数据聚合(多个 API 请求) - Data aggregation in JavaScript, Arrays (Multiple API requests) 如何简化基于属性组合两个数组的 es6 函数? - How do I simplify my es6 function that combines two arrays based on properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM