简体   繁体   English

从使用 lodash 创建的 object 数组中获取 uniq 值

[英]Get uniq values from an array of object created using lodash

I am new to the react, Here I am trying to get the unique elements from the newly created array of object.我是新手,在这里我试图从新创建的 object 数组中获取唯一元素。

const data = _.uniq(
  orderData?.Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  }))
);

I have tried this but, still, it returns me the array of the object which has the unique elements using any of the two keys.我已经尝试过了,但它仍然返回了 object 的数组,它使用两个键中的任何一个键具有唯一元素。

an object should not be duplicated. object 不应重复。

can anyone help me with this?谁能帮我这个?

It should be _.uniqBy() , refer uniqBy应该是_.uniqBy() ,参考uniqBy

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })), 'label' or 'value'
);

It should be either by label or by value它应该是 label 或值

Example例子

 document.querySelector("body").onload = function() { // By 'label' console.log("By label"); console.log( _.uniqBy( [ {'label': 'name', 'value': 'Test Name 1'}, {'label': 'name', 'value': 'Test Name 2'}, {'label': 'company', 'value': 'Test Company 1'} ], 'label' ) ) // By 'vlaue' console.log("By value"); console.log( _.uniqBy( [ {'label': 'name', 'value': 'SO User'}, {'label': 'name', 'value': 'SO User'}, {'label': 'company', 'value': 'Test Company 1'} ], 'value' ) ) }
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

You have to use _.uniqBy(data, 'id');//id that is key you have to remove duplicate value from array你必须使用_.uniqBy(data, 'id');//id that is key you have to remove duplicate value from array

Your Scenario will be used like this您的场景将像这样使用

if removed by a label then如果被label移除,则

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })),'label'
);

if removed by a value then如果被一个移除,那么

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })),'value'
); 

If you get more details then Link如果您获得更多详细信息,请链接

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

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