对象数组拆分为多列表及提取属性值列表的最优方法
Hey there! Let's tackle your two questions one by one:
需求1:将对象数组拆分为多个列表
拆分对象数组的方式完全取决于你的拆分规则,这里给几个常见场景的简洁实现:
按某个属性条件分组(比如把价格高于70和低于等于70的对象分开):
const arr = [{id: 3, price: 77}, {id: 2, price: 66}, {id: 1, price: 88}]; const [highPriceGroup, lowPriceGroup] = arr.reduce((acc, item) => { item.price > 70 ? acc[0].push(item) : acc[1].push(item); return acc; }, [[], []]);执行后就能得到两个独立的对象数组,分别对应符合条件的分组。
按固定数量拆分(比如每2个对象为一组):
const splitBySize = (arr, size) => arr.reduce((acc, item, index) => { const groupIndex = Math.floor(index / size); (acc[groupIndex] || (acc[groupIndex] = [])).push(item); return acc; }, []); const result = splitBySize(arr, 2); // 输出 [[{id:3, price:77}, {id:2, price:66}], [{id:1, price:88}]]
如果你的拆分规则有特殊要求,可以补充细节,但上面是通用且简洁的写法~
需求2:从对象列表提取指定属性的数组
最简洁的实现绝对是用数组的map()方法——它天生就是用来做这种"元素转换"的场景,一行代码搞定:
const objList = [{id: 3, price: 77}, {id: 2, price: 66}]; const priceList = objList.map(item => item.price); // 输出 [77, 66]
map()会遍历数组中的每个对象,自动提取出price属性值并生成新数组。这种写法不仅简洁,可读性也拉满,是前端处理这类属性提取的标准操作。
内容的提问来源于stack exchange,提问作者Mohamed Shaheen
相关产品推荐
相关产品推荐

