首页 > 解决方案 > 如何通过匹配它们的 id 值将 2 个对象组合成一个表?

问题描述

我想知道如何通过将它们的 id 值相互匹配并可能将其转换为表格格式来将两个对象组合在一起。

$genres = [
    {
    "id": 1,
    "type": "KPOP",
    "music_id": 1,
    "created_at": "2020-04-19 10:10:10"
  },
  {
    "id": 3,
    "type": "JPOP",
    "music_id": 3,
    "created_at": "2020-02-14 10:10:10"
  },
  {
    "id": 2,
    "type": "OPM",
    "music_id": 2,
    "created_at": "2020-06-30 10:10:10"
  }
 ];
 
 $countries = [
    {
    "id": 1,
    "country": "South Korea",
    "updated_at" : "2020-04-20 10:10:10"
  },
  {
    "id": 3,
    "country": "Japan",
    "updated_at" : "2020-02-15 10:10:10"
  },
  {
    "id": 2,
    "country": "Philippines",
    "updated_at" : "2020-07-01 10:10:10"
  }
 ];

结果应该是这样排列的(不一定要这样设计,只要是一个简单的表格即可):

+----+--------+--------------------+
| 1  | KPOP   | South Korea        |
+----+--------+--------------------+
| 2  | OPM    | Philippines        |
+----+--------+--------------------+
| 3  | JPOP   | Japan              |
+----+--------+--------------------+

然而,我的解决方案一直在充实错误的组合(还不是表格,因为我不知道如何):

let table = []

 for (let i = 0; i < $genres.length; i++) {
   table.push({
     ...$genres,
     ...$countries.find((countryId) => countryId.id === $genres[i].id )
   });
}

console.log(table)
[
  {
    '0': {
      id: 1,
      type: 'KPOP',
      music_id: 1,
      created_at: '2020-04-19 10:10:10'
    },
    '1': {
      id: 3,
      type: 'JPOP',
      music_id: 3,
      created_at: '2020-02-14 10:10:10'
    },
    '2': {
      id: 2,
      type: 'OPM',
      music_id: 2,
      created_at: '2020-06-30 10:10:10'
    },
    id: 1,
    country: 'South Korea',
    updated_at: '2020-04-20 10:10:10'
  },
  {
    '0': {
      id: 1,
      type: 'KPOP',
      music_id: 1,
      created_at: '2020-04-19 10:10:10'
    },
    '1': {
      id: 3,
      type: 'JPOP',
      music_id: 3,
      created_at: '2020-02-14 10:10:10'
    },
    '2': {
      id: 2,
      type: 'OPM',
      music_id: 2,
      created_at: '2020-06-30 10:10:10'
    },
    id: 3,
    country: 'Japan',
    updated_at: '2020-02-15 10:10:10'
  },
  {
    '0': {
      id: 1,
      type: 'KPOP',
      music_id: 1,
      created_at: '2020-04-19 10:10:10'
    },
    '1': {
      id: 3,
      type: 'JPOP',
      music_id: 3,
      created_at: '2020-02-14 10:10:10'
    },
    '2': {
      id: 2,
      type: 'OPM',
      music_id: 2,
      created_at: '2020-06-30 10:10:10'
    },
    id: 2,
    country: 'Philippines',
    updated_at: '2020-07-01 10:10:10'
  }
]

我想知道如何把它做成一张桌子,但到目前为止我很困惑。先感谢您!

标签: javascript

解决方案


从以 id 为键的国家/地区创建一个对象。然后迭代流派,您可以在国家对象上查找 O(1) 以匹配国家和流派。

const countryObj = $countries.reduce((obj, x) => { obj[x.id] = x; return obj; }, {});

for(let g of $genres.sort((a, b) => a.id - b.id)) { 
    const country = countryObj[g.id]
    if (country !== undefined) {
        console.log([g.id, g.type, country.country].join('|'))
    }
}

这假设所有条目$countries都具有与国家名称一致的属性名称。


推荐阅读