简体   繁体   中英

Spread operator over an array of objects in typescript

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.

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. 在此处输入图像描述

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM