在对象内部展开数组会产生意想不到的结果 - Javascript

Spreading an array inside an object gives unexpected result - Javascript

我有两个具有相同键的对象数组,我想合并它们并创建一个新的对象数组。我几乎可以把所有事情都做对,但是当我想将它们散布到新数组中时就会出现问题。价差自动包含一个键值对,其中包含索引和值,这不是我想要的。我错过了什么?请指教

这是我的实现:

const currentData = [{
  FIRST_NAME: 'ABC',
  MIDDLE_NAME: 'DEF',
  LAST_NAME: 'GHI'
}]

const historicalData = [{
  FIRST_NAME: 'ABC1',
  MIDDLE_NAME: 'DEF1',
  LAST_NAME: 'GHI1'
}, {
  FIRST_NAME: 'ABC2',
  MIDDLE_NAME: 'DEF2',
  LAST_NAME: 'GHI2'
}, {
  FIRST_NAME: 'ABC3',
  MIDDLE_NAME: 'DEF3',
  LAST_NAME: 'GHI3'
}]

const rowDataKeys = Object.keys(currentData[0])

const rowData = rowDataKeys.map((i) => {
  const resp = historicalData.map((j, index) => {
    return {
      [`history${index+1}`]: historicalData[index][i]
    }
  })
  return {
    field: i,
    current: currentData[0][i],
    ...resp
  }
})

console.log(rowData)

预期输出:

[{
    field: 'FIRST_NAME',
    current: 'ABC',
    history1: 'ABC1',
    history2: 'ABC2',
    history3: 'ABC3'
}, {
    field: 'MIDDLE_NAME',
    current: 'DEF',
    history1: 'DEF1',
    history2: 'DEF2',
    history3: 'DEF3'
}, {
    field: 'LAST_NAME',
    current: 'GHI',
    history1: 'GHI1',
    history2: 'GHI2',
    history3: 'GHI3'
}]

数组[a, b, c]作为对象{ '0': a, '1': b, '2': c }散布在对象内部,索引为键,元素为值。您可以使用 reduce 创建对象。

const currentData = [{
  FIRST_NAME: 'ABC',
  MIDDLE_NAME: 'DEF',
  LAST_NAME: 'GHI'
}]

const historicalData = [{
  FIRST_NAME: 'ABC1',
  MIDDLE_NAME: 'DEF1',
  LAST_NAME: 'GHI1'
}, {
  FIRST_NAME: 'ABC2',
  MIDDLE_NAME: 'DEF2',
  LAST_NAME: 'GHI2'
}, {
  FIRST_NAME: 'ABC3',
  MIDDLE_NAME: 'DEF3',
  LAST_NAME: 'GHI3'
}]

const rowDataKeys = Object.keys(currentData[0])

const rowData = rowDataKeys.map((i) => {
  const resp = historicalData.reduce((acc, j, index) => {
    acc[`history${index+1}`] = historicalData[index][i];
    return acc;
  }, {})
  return {
    field: i,
    current: currentData[0][i],
    ...resp
  }
})

console.log(rowData)

之前代码片段中的resp类型是对象数组。

const resp = historicalData.map((j, index) => {
  return {
    [`history${index+1}`]: historicalData[index][i]
  }
});

您可能希望类型直接成为一个对象。

您可以为此使用 Array.reduce

const currentData = [{
  FIRST_NAME: 'ABC',
  MIDDLE_NAME: 'DEF',
  LAST_NAME: 'GHI'
}]

const historicalData = [{
  FIRST_NAME: 'ABC1',
  MIDDLE_NAME: 'DEF1',
  LAST_NAME: 'GHI1'
}, {
  FIRST_NAME: 'ABC2',
  MIDDLE_NAME: 'DEF2',
  LAST_NAME: 'GHI2'
}, {
  FIRST_NAME: 'ABC3',
  MIDDLE_NAME: 'DEF3',
  LAST_NAME: 'GHI3'
}]

const rowDataKeys = Object.keys(currentData[0])

const rowData = rowDataKeys.map((i) => {
  const resp = historicalData.reduce((acc, j, index) => ({
    ...acc,
    [`history${index+1}`]: historicalData[index][i],
  }), {})
  return {
    field: i,
    current: currentData[0][i],
    ...resp
  }
})

console.log(rowData)