Home > Enterprise >  How to add elements to array in object property
How to add elements to array in object property

Time:08-10

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?

CodePudding user response:

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;
}, {})

CodePudding user response:

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

  • Related