合并具有重复项的对象数组中的对象

问题描述 投票:0回答:1

我有“可用”数据,想将其转换为“所需”数据。

我尝试使用 this 合并数组内的所有对象,但它不起作用,因为正如您所见,时间戳 = 10 我们有 2 个 sw_version 值

const available = [
    {
      "timestamp": 10,
      "sw_version": "AA"
    },
    {
      "timestamp": 10,
      "sw_version": "AB"
    },
    {
      "timestamp": 20,
      "sw_version": "QFX-1.2.5 B"
    },
    {
      "timestamp": 10,
      "pressure": 14.75
    },
    {
      "timestamp": 20,
      "pressure": 14.22
    },
    {
      "timestamp": 10,
      "temperature": 15.96
    },
    {
      "timestamp": 20,
      "temperature": 38.50
    }
  ]

const desired = [
    {
      "timestamp": 10,
      "sw_version": "AA",
      "pressure": 14.75,
      "temperature": 15.96
    },
    {
      "timestamp": 10,
      "sw_version": "AB",
      "pressure": 14.75,
      "temperature": 15.96
    },
    {
      "timestamp": 20,
      "sw_version": "QFX-1.2.5 B",
      "pressure": 14.22,
      "temperature": 38.5
    }
  ]

const output = available.reduce((result, item) => {
      const i = result.findIndex((resultItem) => resultItem.timestamp === item.timestamp);
      if (i === -1) {
        result.push(item);
      } else {
        result[i] = { ...result[i], ...item };
      }
      return result;
    }, []);
    
console.log(output)

输出是

[
    {
        "timestamp": 10,
        "sw_version": "AB",
        "pressure": 14.75,
        "temperature": 15.96
    },
    {
        "timestamp": 20,
        "sw_version": "QFX-1.2.5 B",
        "pressure": 14.22,
        "temperature": 38.5
    }
]

正如您在所需的输出中看到的,我想要 2 个时间戳 = 10 的对象,但在函数输出中,它会覆盖第一个对象并仅保留一个对象。

此外,我们可能会获得时间戳的第二个压力或温度值,其中我们已经有了像 sw_version 这样的测量值

javascript arrays array-merge
1个回答
0
投票

可以这样做:

const available = 
  [ { timestamp: 10, sw_version: 'AA'          } 
  , { timestamp: 10, sw_version: 'AB'          } 
  , { timestamp: 20, sw_version: 'QFX-1.2.5 B' } 
  , { timestamp: 10, pressure:    14.75        } 
  , { timestamp: 20, pressure:    14.22        } 
  , { timestamp: 10, temperature: 15.96        } 
  , { timestamp: 20, temperature: 38.50        } 
  ];

const result = available.reduce( (res, { timestamp, sw_version, ...props }) =>
  {
  if ( !!sw_version )
    {
    res.push( { timestamp, sw_version  });
    }
  else
    {
    res.filter( elm => elm.timestamp === timestamp )
       .forEach( line => Object.assign(line, props));  
    }
  return res;
  }
  ,[]);

console.log( JSON.stringify(result,0,2))
.as-console-wrapper { max-height: 100% !important; top: 0; }

© www.soinside.com 2019 - 2024. All rights reserved.