javascript - 合并两个数组对象:一个有键值对,另一个只是数组
问题描述
我有两个数组对象,一个是 ArrayX,另一个是 ArrayY。ArrayX 有 user_id 和 store_ids[] 并且 ArrayY 有 store_id 和 store_name 我想根据 ArrayX 的 store_ids 合并这两个数组。
```
//First array
ArrayX = [
{
user_id: 'user 4',
store_ids: [ 'store 2','store 4', 'store 1' ],
},
{
user_id: 'user 6',
store_ids: [ 'store 1', 'store 2' ],
}
]
//second array
ArrayY = [
{
store_id: 'store 4',
store_name: 'store D'
},
{
store_id: 'store 2',
store_name: 'store B'
},
{
store_id: 'store 1',
store_name: 'store A'
},
{
store_id: 'store 3',
store_name: 'store C'
}
]
```
我想要的在下面给出。
```
ArrayZ = [
{
user_id: 'user 4',
store_ids: [ 'store 2','store 4', 'store 1' ],
store_info : [
{
store_id: 'store 2',
store_name: 'store B'
},
{
store_id: 'store 4',
store_name: 'store D'
},
{
store_id: 'store 1',
store_name: 'store A'
}
]
},
{
user_id: 'user 6',
store_ids: [ 'store 1', 'store 2' ],
store_info: [
{
store_id: 'store 1',
store_name: 'store A',
},
{
store_id: 'store 2',
store_name: 'store B',
}
]
}
]
```
我尝试了 map 功能,但没有得到上面提到的预期结果。
let ArrayZ = ArrayX.map((item, i) => Object.assign({}, item, ArrayY[i]))
[
{
user_id: 'user 4',
store_ids: [ 'store 2', 'store 4','store 1' ],
store_id: 'store 4',
store_name: 'store D',
},
{
user_id: 'user 6',
store_ids: [ 'store 1', 'store 2'],
store_id: 'store 2',
store_name: 'store B',
},
Thi is what i am getting.
任何人都可以对此提出建议。
解决方案
您可以为所有商店获取一个对象,然后将新对象映射到商店名称。
这种方法只需要两个循环。
const
array1 = [{ user_id: 'user 4', store_ids: ['store 2', 'store 4', 'store 1'] }, { user_id: 'user 6', store_ids: ['store 1', 'store 2'] }],
array2 = [{ store_id: 'store 4', store_name: 'store D' }, { store_id: 'store 2', store_name: 'store B' }, { store_id: 'store 1', store_name: 'store A' }, { store_id: 'store 3', store_name: 'store C' }],
stores = Object.fromEntries(array2.map(o => [o.store_id, o])),
result = array1.map(o => ({ ...o, store_info: o.store_ids.map(id => stores[id]) }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- swiftui - 无法在 ListView SwiftUI 中使用按钮工作表
- javascript - 用于高图位置的自定义 SVG 符号
- python - 如何使用不同数量的 python 值编写 CSV
- c++ - c++中幂函数的奇怪行为
- java - 不同模块的版本 gradle
- javascript - 在javascript中将多个二维数组合并为一个二维数组
- chart.js - Chart.js:截断图例的标签
- python - 为什么这个多类 LSTM 分类器的准确率低?
- c# - 如何将新字段添加到来自 nuget 包的现有模型
- python - 使用 IF 样式语句从选择的其他列中创建一列