javascript - 如何通过匹配它们的 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'
}
]
我想知道如何把它做成一张桌子,但到目前为止我很困惑。先感谢您!
解决方案
从以 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
都具有与国家名称一致的属性名称。
推荐阅读
- google-speech-api - 如何提高 Google Speech to Text API 中的标点和类标记的准确性
- angular - 在规范文件中运行多个测试时发出清理组件角度
- typescript - 打字稿和 Firebase 9
- javascript - 元素 scrollIntoView 在 Safari 中不起作用
- android - 如何在没有任何密码的情况下在 Flutter 中解密和删除 pdf 的有限权限?
- javascript - 如何创建以下样式的按钮?
- python - 如何在 Matplotlib 中打印带有标题的图像?
- excel - 在 Visual Basic for Excel 中使用字符串文本作为代码
- c# - 正则表达式匹配字母数字,除了特定的子字符串
- javascript - 如何使用带有 CORS 或 API 凭据的 javascript 从 Google Drive 共享 mp3 文件