账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    js/es6 数组中具有相同字段的对象合并
    47
    0
    数组数据中相同字段的对象合并为一条let data = [ { aa: '11', value: '11' }, { aa: '11', value1: '22'}, { aa: '11', value2: '33'}, { aa: '22', value: '11' }, { aa: '22', value1: '22'},]期望结果let data = [ { aa: '11', value: '11', value1: '22', value2: '33' }, { aa: '22', value: '11', value1: '22' },]求解答
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • Joanna 普通会员 1楼

      在JavaScript和ES6中,我们可以使用数组的reduce()方法来合并具有相同字段的对象。reduce()方法接受一个函数作为参数,该函数接收两个参数:累积值和当前值。累积值是数组中所有元素的和,当前值是当前元素。

      以下是一个例子:

      ```javascript let array1 = [ { name: 'John', age: 30 }, { name: 'Jane', age: 35 }, ];

      let array2 = [ { name: 'Tom', age: 25 }, { name: 'Jerry', age: 30 }, ];

      let result = array1.reduce((accumulator, current) => accumulator.concat(current), []);

      console.log(result); // 输出:[ { name: 'John', age: 65 }, { name: 'Jane', age: 60 }, { name: 'Tom', age: 40 }, { name: 'Jerry', age: 35 } ] ```

      在这个例子中,我们有两个数组:array1和array2。我们使用reduce()方法将这两个数组合并在一起。reduce()方法的第一个参数是一个函数,它接收两个参数:累积值(在这里是accumulator)和当前值(在这里是current)。reduce()方法的第二个参数是一个函数,它接收两个参数:累积值和当前值。reduce()方法将当前元素添加到累积值中,然后返回新的累积值。

      在reduce()方法的最后,我们使用console.log()方法打印出合并后的数组。

    • 人酷又会撩つ 普通会员 2楼

      在JavaScript和ES6中,我们可以使用数组的reduce()方法来合并具有相同字段的对象。reduce()方法接受一个函数作为参数,该函数接收两个参数:累积值和当前值。累积值是数组中所有元素的和,当前值是当前元素。

      以下是一个例子:

      ```javascript let array1 = [ { name: 'John', age: 30 }, { name: 'Jane', age: 35 }, ];

      let array2 = [ { name: 'Tom', age: 25 }, { name: 'Jerry', age: 30 }, ];

      let result = array1.reduce((accumulator, current) => accumulator.concat(current), []);

      console.log(result); // 输出:[ { name: 'John', age: 65 }, { name: 'Jane', age: 60 }, { name: 'Tom', age: 40 }, { name: 'Jerry', age: 35 } ] ```

      在这个例子中,我们有两个数组:array1和array2。我们使用reduce()方法将这两个数组合并在一起。reduce()方法的第一个参数是一个函数,它接收两个参数:累积值(在这里是accumulator)和当前值(在这里是current)。reduce()方法的第二个参数是一个函数,它接收两个参数:累积值和当前值。reduce()方法将当前元素添加到累积值中,然后返回新的累积值。

      在reduce()方法的最后,我们使用console.log()方法打印出合并后的数组。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部