Объединить два объекта массива: один имеет пару значений ключа, а другой — просто массив

#javascript

#javascript

Вопрос:

У меня есть два объекта массива, один из которых — ArrayX, а другой — ArrayY. У ArrayX есть user_id и store_ids[], а у ArrayY есть store_id и store_name Я хочу объединить оба массива в соответствии с store_ids ArrayX.

 ```
//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.
  

кто-нибудь может что-нибудь предложить по этому поводу.

Ответ №1:

Вот как я бы это сделал:

 const arrayZ = [];

const sort = () =>{
    
    arrayX.forEach(element => {
        let store_info = [];
        arrayY.forEach(el =>{
            if(element.store_ids.includes(el.store_id)){
                store_info.push(el);
                console.log(store_info)
            }
        })
        element.store_info = store_info;
        arrayZ.push(element);
    })
} 

sort();

console.log(arrayZ);    

  

Вы даже можете немного реорганизовать функцию, чтобы принять 2 массива в качестве аргументов….
Таким образом, вы сохраняете как arrayX, так и arrayY без изменений, если вам это нужно…

Ответ №2:

Вы можете взять объект для всех хранилищ, а затем сопоставить новые объекты с именами хранилищ.

Этот подход требует только двух циклов.

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

Комментарии:

1. Спасибо за усилия, приятель, но этот скрипт не дает точного объекта массива, который я хотел. проверьте первое предложение.

Ответ №3:

Я всегда пишу следующим образом. Я думаю, что это читаемо.

     const ArrayZ = ArrayX.map((x) => {
      const store_infos = [];
      for (const store_id of x.store_ids) {
        const store_info = ArrayY.find((y) => y.store_id === store_id);
        store_infos.push(store_info);
      }

      return {
        user_id: x.user_id,
        store_ids: x.store_ids,
        store_info: store_infos,
      };
    });

    console.log(JSON.stringify(ArrayZ, null, 2));