Home > Net >  How to make object which store unique key have multiple different values
How to make object which store unique key have multiple different values

Time:02-03

    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']
  }

CodePudding user response:

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

CodePudding user response:

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