如何为对象数组中相邻同Quantity元素添加Count统计字段?
解决方案
要实现仅统计相邻相同Quantity值的元素数量并添加Count字段,可以按照以下逻辑编写代码:
代码实现
let myData = [ { Name: 'Section 1', Details:[ { Product: 'Ballpen', Quantity: 120}, { Product: 'Pencil', Quantity: 120}, { Product: 'Marker', Quantity: 80}, { Product: 'Highlighter', Quantity: 120} ] }, { Name: 'Section 2', Details:[ { Product: 'Paper', Quantity: 40}, { Product: 'Bond Paper', Quantity: 75}, { Product: 'Colored Paper', Quantity: 75}, { Product: 'Oslo paper', Quantity: 40} ], } ]; // 处理每个分区的数据 myData.forEach(section => { const details = section.Details; if (details.length === 0) return; // 第一步:标记每个相邻分组的数量 const groupCounts = []; let currentQty = details[0].Quantity; let currentCount = 1; for (let i = 1; i < details.length; i++) { if (details[i].Quantity === currentQty) { currentCount++; } else { // 把当前分组的数量重复对应次数存入数组 for (let j = 0; j < currentCount; j++) { groupCounts.push(currentCount); } currentQty = details[i].Quantity; currentCount = 1; } } // 处理最后一个分组 for (let j = 0; j < currentCount; j++) { groupCounts.push(currentCount); } // 第二步:给每个元素添加Count字段 details.forEach((item, index) => { item.Count = groupCounts[index]; }); // 按要求格式输出到控制台 console.log(`${section.Name} : {`); details.forEach(item => { console.log(` [ Product = '${item.Product}', Quantity = ${item.Quantity} , Count = ${item.Count}],`); }); console.log('},'); });
逻辑说明
- 分组统计:遍历
Details数组,跟踪当前连续的Quantity值和计数,遇到不同值时,将当前计数重复对应次数存入groupCounts,确保每个元素对应自己所在分组的数量。 - 添加字段:将
groupCounts中的值依次赋值给每个元素的Count属性。 - 格式输出:按照你需要的结构打印处理后的数据。
运行结果
控制台会输出:
Section 1 : { [ Product = 'Ballpen', Quantity = 120 , Count = 2], [ Product = 'Pencil', Quantity = 120 , Count = 2], [ Product = 'Marker', Quantity = 80 , Count = 1], [ Product = 'Highlighter', Quantity = 120 , Count = 1], }, Section 2 : { [ Product = 'Paper', Quantity = 40 , Count = 1], [ Product = 'Bond Paper', Quantity = 75 , Count = 2], [ Product = 'Colored Paper', Quantity = 75 , Count = 2], [ Product = 'Oslo paper', Quantity = 40 , Count = 1], },
处理后的myData中每个Details元素都新增了Count字段,可直接用于表格渲染。
内容的提问来源于stack exchange,提问作者Keyboard Corporation
相关产品推荐
相关产品推荐

