You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS中按条件转换对象数组的实现方法

数组分组解决方案

可以通过遍历数组,将每个contact类型的对象与其后续连续的representative对象分组,实现代码如下:

const originalArray = [
    { "country": "UK", "name": "Battery Ltd 1", "type": "contact" },
    { "country": "USA", "name": "Technologies Inc. 1", "type": "contact" },
    { "country": "", "name": "Jayne Mansfield", "type": "representative" },
    { "country": "China", "name": "Technologies Inc. 2", "type": "contact" },
    { "country": "", "name": "Dan Borrington", "type": "representative" },
    { "country": "", "name": "Susan Reedy", "type": "representative" }
];

const result = [];
let i = 0;

while (i < originalArray.length) {
    // 遇到contact时创建新分组
    if (originalArray[i].type === 'contact') {
        const group = [originalArray[i]];
        i++;
        // 收集后续所有连续的representative
        while (i < originalArray.length && originalArray[i].type === 'representative') {
            group.push(originalArray[i]);
            i++;
        }
        result.push(group);
    } else {
        // 若数组开头非contact,跳过(可根据需求调整处理逻辑)
        i++;
    }
}

console.log(result);

逻辑说明

  1. 初始化结果数组result和遍历索引i
  2. 外层循环遍历原数组,遇到contact类型对象时创建新分组数组
  3. 内层循环收集当前contact之后所有连续的representative对象,加入当前分组
  4. 将分组数组推入结果数组,直到遍历完整个原数组

执行上述代码后,即可得到你需要的嵌套数组格式。

内容的提问来源于stack exchange,提问作者Владислав Петров

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:20:38