0
    var data = [{type: 'physical', value: 'verified'}, 
                {type: 'reference', value: 'owner'},
                {type: 'physical', value: 'pending'},
                {type: 'document', value: 'pending'}
               ]

How to return object in such a way which should have unique key which store mulpltiple values

Expected Result =

  var data  = {
      physical: ['verified', 'pending'],
      reference: ['owner'],
      document: ['pending']
  }
raghav kumar
  • 106
  • 5
  • Does this answer your question? [javascript - find unique objects in array based on multiple properties](https://stackoverflow.com/questions/38613654/javascript-find-unique-objects-in-array-based-on-multiple-properties) – shrys Feb 03 '23 at 14:08
  • Please share the expected results based on the data you supplied. – M0nst3R Feb 03 '23 at 14:09
  • Can you show us what you tried? Even if it doesn't work at all. – M0nst3R Feb 03 '23 at 14:14
  • Expected result = ```var data = { physical: ['verified', 'pending'], reference: ['owner'], document: ['pending'] }``` – raghav kumar Feb 03 '23 at 14:17
  • @GhassenLouhaichi I tried but didn't work for me with this code `var hashMap = {} for (const i of data) { hashMap[i.type] = i } return hashMap` – raghav kumar Feb 03 '23 at 14:19

2 Answers2

1

You can reduce the data array to an object and build the properties as well as the values in each property using spread operator, destructuring, and nullish coalescing.

data.reduce((acc, { type, value }) => ({
    ...acc,
    [type]: [...(acc[type] ?? []), value]
}), {});
M0nst3R
  • 5,186
  • 1
  • 23
  • 36
0

this function should return the result as you asked.

function getUnique(data){
    let x = {};
    for(let i of data){
        if (!x[i.type]){x[i.type] = [];}
        x[i.type].push(i.value);
    }
    return x;
}
Chaitanya Mankala
  • 1,594
  • 17
  • 24