簡體   English   中英

創建新的 object 數組並將對象合並到具有相同鍵值的數組 object 中

[英]Create new object array and merge objects into array object with same key value

這可能看起來有點奇怪,但我需要將現有數據集中的對象合並到按特定鍵值分組的新數據集中。 這是數據集:

const object = [
  {
    id: 1,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 1'
    }
  },
  {
    id: 2,
    scheduledAt: '2022-09-10',
    organization: {
      name: 'Organization 2'
    } 
  },
  {
    id: 3,
    scheduledAt: '2022-09-20',
    organization: {
      name: 'Organization 3'
    }
  }
]

這是我作為返回數據集所追求的:

const objectMerged = {
  '2022-09-20': [
    {
      id: 1,
      scheduledAt: '2022-09-20',
      organization: {
        name: 'Organization 1'
      }
    },
    {
      id: 3,
      scheduledAt: '2022-09-20',
      organization: {
        name: 'Organization 3'
      }
    }
  ],
  '2022-09-10': [
    {
      id: 2,
      scheduledAt: '2022-09-10',
      organization: {
        name: 'Organization 2'
      } 
    }
  ]
}

我嘗試了許多不同的方法,但似乎沒有任何工作正常。 這是最新的代碼,它不起作用:

const merged = []

object.forEach((item) => {
  if (!merged.length) {
    // if the return dataset is empty, add this item immediately
    merged.push({ [item.scheduledAt]: [item] }
  } else {
    // check if item already exists with the same scheduledAt as current object and if so, push it into that array as object
    // if does not exist, create new array entry with the new scheduledAt name

    const find = Object.keys(merged).map((k) => {
      console.log(`key ${k}`)
      console.log(merged[k])
    
      return Object.keys(merged[k]).map((key) => {
        console.log(`key2: ${key}`)
    
        return key === item.scheduledAt
      })
    })

    console.log(find)
  }
})

console.log(merged)

任何幫助是極大的贊賞。 謝謝!

通過使用 reduce,您可以生成所需的內容。 請看一看:

 const object = [ { id: 1, scheduledAt: '2022-09-20', organization: { name: 'Organization 1' } }, { id: 2, scheduledAt: '2022-09-10', organization: { name: 'Organization 2' } }, { id: 3, scheduledAt: '2022-09-20', organization: { name: 'Organization 3' } }, ]; const objectMerged = object.sort((objectA, objectB) => objectA.scheduledAt.localeCompare(objectB.scheduledAt) ).reduce((acc, cur) => ({...acc, [cur.scheduledAt]: [...(acc[cur.scheduledAt] || []), cur, ], }), {}); console.log(objectMerged);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM