简体   繁体   English

在 typescript 中的对象数组上展开运算符

[英]Spread operator over an array of objects in typescript

I am trying to use spread operator to find a unique set on this我正在尝试使用spread operator来找到一个唯一的集合

 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?您可以从此处如何从 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.除非object具有same的引用,否则您无法使用Set找到unique objects So in your case it seems you are having two different references for both objects inside array.因此,在您的情况下,您似乎对数组中的两个objects都有两个不同的references Thus Set will return 2 values .因此Set将返回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.如果您对两个objects都有samereference (例如 let o = {id: 'p1',isOptional: false,item: [Object]})并且 let obj = {requests: [o,o]}那么它将返回唯一值。

You can verify the same at Set as below screenshot.您可以在Set中进行验证,如下图所示。 在此处输入图像描述

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 .您可以通过使用带有mapfilterspread Operator来执行此操作。 Just using a spread operator with new Set will not give the desired results.仅使用带有new Set的扩展运算符不会产生预期的结果。

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使用扩展运算符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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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