参考来源:javascript - 如何把数组对象相同的key值合并,并且把对应的id放到一个数组 - SegmentFault 思否
1、原数据:
2、方式一:const old = [ {id: 1, name: 'css', type: 'html'}, {id: 2, name: 'css', type: 'html'}, {id: 3, name: 'javacript', type: 'code'}, {id: 4, name: 'javacript', type: 'code'} ]; const newData = [ {ids: [1,2], name: 'css', type: 'html'}, {ids: [3,4], name: 'javacript', type: 'code'} ];
const obj = {} , res = []; let n = 0; old.forEach(function(element) { const {id, name} = element; obj[name] ? res[obj[name] - 1].ids.push(id) : obj[name] = ++n && res.push({ ids: [id], name: name, type: element.type }); });
3、方式二:
reduce()
方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。具体可参考:Array.prototype.reduce() - JavaScript | MDNreducer 函数接收4个参数:
- Accumulator (acc) (累计器)
- Current Value (cur) (当前值)
- Current Index (idx) (当前索引)
- Source Array (src) (源数组)
您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
语法
arr.reduce( callback(accumulator, currentValue[, index[, array]]) [, initialValue] )
参数
(1) callback:
执行数组中每个值 (如果没有提供initialValue,则第一个值除外
)的函数,包含四个参数:
<1> accumulator:
累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue
(见于下方)。
<2> currentValue:
数组中正在处理的元素。
<3> index:
可选,数组中正在处理的当前元素的索引。 如果提供了initialValue
,则起始索引号为0,否则从索引1起始。
<4> array:
可选,调用reduce()
的数组
(2)initialValue:
可选,作为第一次调用callback
函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。返回值
函数累计处理的结果
const isEqual = (a, b) => (a.name === b.name && b.type === b.type); const create = e => { e.id = [e.id]; return e; } const getNew = old => old.reduce((prev, curr) => { let hasItem = prev.some(e => { let temp = isEqual(e, curr); if (temp) e.id.push(curr.id); return temp; }); if (!hasItem) { prev.push(create(curr)); } return prev; }, []); const newArr = getNew(old);
如何把数组对象中相同的key值合并,并且把对应的id放到一个数组中
于 2021-01-26 14:13:47 首次发布