简体   繁体   中英

How to add elements to array in object property

I have the following array and object I would like to 'match'

const items = [
  { key: 1, name: 'A', owner: 'Alex', },
  { key: 2, name: 'B', owner: 'Barb', },
  { key: 3, name: 'C', owner: 'John', },
  { key: 4, name: 'D', owner: 'Barb', },
  { key: 5, name: 'E', owner: 'Alex', },
];

const owners = {
  'Alex': { 1: [], 5: [] },
  'John': { 3: [], },
  'Barb': { 2: [], 4: [] },
}

I would like to have the following end result:

const ownersWithName = {
  'Alex': [{ key: 1, name: 'A', }, { key: 5, name: 'E' }],
  'Barb': [{ key: 2, name: 'B', }, { key: 4, name: 'D' }],
  'John': [{ key: 3, name: 'C', }, ],
}

So far my solution is this:

function matchOwners (items, owners) {
  const ownersWithName = {};
  for (const item of items) {
    if (owners[item.owner]) {
      if (ownersWithName[item.owner]) {
        ownersWithName[item.owner] = [ ...ownersWithName[item.owner], item];
      } else {
        ownersWithName[item.owner] = [item];
      }
    }
  }
  return ownersWithName;
}

This solution works, but i feel it's too verbose. i tried to use the spread operator without the if condition, but this needs the array to exist already, otherwise i get the error ownersWithName[item.owner] is not iterable . Is there a better way to do this?

Something like (completely untested):

ownersWithName = items.reduce((result, item) => { 
  if (owners[item.owner]) {
    if (!(item.owner in result)) {
      result[item.owner] = [];
    }
    result[item.owner].push({key: item.key, name: item.name});
  }
  return result;
}, {})

You can also simply achieve this by using Array.forEach() along with the Object.keys() method.

Live Demo (Descriptive comments has been added in the below code snippet) :

 // Input array const items = [ { key: 1, name: 'A', owner: 'Alex', }, { key: 2, name: 'B', owner: 'Barb', }, { key: 3, name: 'C', owner: 'John', }, { key: 4, name: 'D', owner: 'Barb', }, { key: 5, name: 'E', owner: 'Alex', }, ]; // Input object which should be used to match. const owners = { 'Alex': { 1: [], 5: [] }, 'John': { 3: [], }, 'Barb': { 2: [], 4: [] }, }; // Declare an object which will store the final result. const resultObj = {}; // Iterating over an items array to manipulate the data and make the final result set. items.forEach(obj => { resultObj[obj.owner] =.resultObj[obj?owner]: []. resultObj[obj;owner]. Object.keys(owners[obj.owner]).forEach(key => { if (key == obj.key) { resultObj[obj.owner]:push({ key. obj,key: name. obj;name }); } }); }). // Final output console;log(resultObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM