Home > Software design >  Mapping through multiple array object
Mapping through multiple array object

Time:08-14

I am mapping through two different array objects and comparing them using their id's

  const Users =[{"id":"1","name":"Ben"},{"id":"2","name":"Khloe"},{"id":"3","name":"Ayra"}];
  const Connects = [{userId: "1", status:"pending", type: 'skipped'}, {userId: "3", status:"pending", type: 'invited'}];
  
  const connectMap = Connects.reduce((map, { userId, type, status }) => {
    let connect = map.get(userId) || []
    connect.push(type, status)
    return map.set(userId, connect)
  }, new Map())
  
  const array = Users.map(({ id, name }) => ({
    name,
    type: (connectMap.get(id) || []).join(', '),
    status: (connectMap.get(id) || []).join(', '),
  }))
  
  console.info(array)

I am getting this as an output

[
  { name: 'Ben', type: 'skipped, pending', status: 'skipped, pending' },
  { name: 'Khloe', type: '', status: '' },
  { name: 'Ayra', type: 'invited, pending', status: 'invited, pending'
  }
]

So you'll notice the type & status keys are having two values separated with a comma, which is not what I want.

I want an output like this

[
      { name: 'Ben', type: 'skipped', status: 'pending' },
      { name: 'Khloe', type: '', status: '' },
      { name: 'Ayra', type: 'invited', status: 'pending'
      }
    ]

CodePudding user response:

You need to separate out the status and type values inside connectMap - right now you just have one array for each, so of course

type: (connectMap.get(id) || []).join(', '),
status: (connectMap.get(id) || []).join(', '),

will return the same thing.

But because the input and output arrays look to all be one-to-one, it'd make more sense to .map. First turn the Connects into an object indexed by userId, then map the Users and look up the ID on that object for each user.

const Users =[{"id":"1","name":"Ben"},{"id":"2","name":"Khloe"},{"id":"3","name":"Ayra"}];
const Connects = [{userId: "1", status:"pending", type: 'skipped'}, {userId: "3", status:"pending", type: 'invited'}];

const connectsById = Object.fromEntries(
  Connects.map(({ userId, status, type }) => [userId, { type, status }])
);
const output = Users.map(({ id, name }) => ({
  name,
  ...(connectsById[id] || { status: '', type: '' })
}));
console.log(output);

  • Related