简体   繁体   English

如何通过对象数组 javascript 中的特定公共属性合并对象的 arrays

[英]how merge arrays of objects by specific common property in on array of objects javascript

I want merge bellow arrays based on hour property and result should be a array of objects我想基于小时属性合并波纹管 arrays,结果应该是一个对象数组

 let sale = [
        {hour: '00', sale: 1514},
        {hour: '01', sale: 1038},
        {hour: '02', sale: 646},
        {hour: '03', sale: 344}
    ]
    let charge = [
        {hour: '00', charge: 1514},
        {hour: '01', charge: 1038},
        {hour: '02', charge: 646},
        {hour: '03', charge: 344}
    ]
    let errors = [
        {hour: '00', errors: 1514},
        {hour: '01', errors: 1038},
        {hour: '02', errors: 646},
        {hour: '03', errors: 344}
    ]

and convert to并转换为

  let all = [
        {hour: '01', sale: 1514, errors: 1038, charge: 646},
        {hour: '02', sale: 1514, errors: 646, charge: 646},
        {hour: '03', sale: 1514, errors: 344, charge: 646}
    ]

You could use an object for grouping the hours and get the values from the object as result.您可以使用 object 对小时进行分组,并从 object 中获取值作为结果。

 const sale = [{ hour: '00', sale: 1514 }, { hour: '01', sale: 1038 }, { hour: '02', sale: 646 }, { hour: '03', sale: 344 }], charge = [{ hour: '00', charge: 1514 }, { hour: '01', charge: 1038 }, { hour: '02', charge: 646 }, { hour: '03', charge: 344 }], errors = [{ hour: '00', errors: 1514 }, { hour: '01', errors: 1038 }, { hour: '02', errors: 646 }, { hour: '03', errors: 344 }], result = Object.values([...sale, ...charge, ...errors].reduce((r, o) => { r[o.hour] = {...r[o.hour], ...o }; return r; }, {})); console.log(result);

I decided share my experience - I solved it by the code below我决定分享我的经验 - 我通过下面的代码解决了它

 let sale = [ {hour: '00', sale: 1514}, {hour: '01', sale: 1038}, {hour: '02', sale: 646}, {hour: '03', sale: 344} ]; let charge = [ {hour: '00', charge: 1514}, {hour: '01', charge: 1038}, {hour: '02', charge: 646}, {hour: '03', charge: 344} ]; let errors = [ {hour: '00', errors: 1514}, {hour: '01', errors: 1038}, {hour: '02', errors: 646}, {hour: '03', errors: 344} ]; let merge = [...sale, ...charge, ...errors] let obj = [] for (let i = 0; i < 4; i++) { let obj2 = {} for (let x of merge) { if (parseInt(x.hour) === i) { Object.assign(obj2, x); } } if (obj2) obj.push(obj2) } console.log(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM