-2

I am trying to use spread operator to find a unique set on this

let obj = {
  requests: [{
      id: 'p1',
      isOptional: false,
      item: [Object]
    },
    {
      id: 'p1',
      isOptional: false,
      item: [Object]
    }
  ]
};

// I tried below.
let output = [...new Set(obj.requests)];
console.log(output);

But that did not work.

Always Helping
  • 14,316
  • 4
  • 13
  • 29
Prakhar
  • 530
  • 10
  • 24

2 Answers2

1

You may get your answer to your question from here How to get distinct values from an array of objects in JavaScript?. Below is explanation why it didn't work as you have expected.

You can not find unique objects with using Set unless they both object are having same reference. So in your case it seems you are having two different references for both objects inside array. Thus Set will return 2 values.

If you are having same reference for both objects (for eg. let o = {id: 'p1',isOptional: false,item: [Object]}) and let obj = {requests: [o,o]} then it will return unique values.

You can verify the same at Set as below screenshot. enter image description here

Consider below sample.

let o = {
  id: 'p1',
  isOptional: false,
  item: {
    id: 10
  }
};

let obj = {
  requests: [o, o]
}

let output = [...new Set(obj.requests)];
console.log('Output with unique reference');
console.log(output);

let o2 = {
  id: 'p1',
  isOptional: false,
  item: {
    id: 10
  }
};

let obj2 = {
  requests: [o, o2]
}
let output2 = [...new Set(obj2.requests)];
console.log('Output with different references');
console.log(output2);
Karan
  • 12,059
  • 3
  • 24
  • 40
0

You can do this either by using filter or spread Operator with map. Just using a spread operator with new Set will not give the desired results.

Using filter

var data = {
  requests: [{
      id: 'p1',
      isOptional: false,
      item: [Object]
    },
    {
      id: 'p1',
      isOptional: false,
      item: [Object]
    }
  ]
}

var unique = data.requests.filter(function({id}) {
  return !this[id] && (this[id] = id)
}, {})

console.log(unique )

Using Spread operator and map

var data = {
  requests: [{
      id: 'p1',
      isOptional: false,
      item: [Object]
    },
    {
      id: 'p1',
      isOptional: false,
      item: [Object]
    }
  ]
}

var unique = [...new Set(data.requests.map(({id}) => id))].map(e => data.requests.find(({id}) => id == e)); 

console.log(unique )
Always Helping
  • 14,316
  • 4
  • 13
  • 29