首页 > 解决方案 > 合并两个数组对象:一个有键值对,另一个只是数组

问题描述

我有两个数组对象,一个是 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.

任何人都可以对此提出建议。

标签: javascript

解决方案


您可以为所有商店获取一个对象,然后将新对象映射到商店名称。

这种方法只需要两个循环。

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; }


推荐阅读