Get uniq values from an array of object created using lodash - javascript

I am new to the react, Here I am trying to get the unique elements from the newly created array of 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.
an object should not be duplicated.
can anyone help me with this?

It should be _.uniqBy(), refer 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
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
Your Scenario will be used like this
if removed by a label then
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

Related

How to Filter object and get certain field in Javascript

I'm struggle with using filter.
Initial object
This is my object.
[{
isOpen : true,
items : [
{itemId : '', name : 'some name'},
{itemId : 'new', name : 'new name'}
]
},]
Expected Result
I just want to show that the itemId is not an empty string and also isOpen field.
[{
isOpen : true,
items : [
{itemId : 'new', name : 'new name'}
]
},]
What I try
const removeEmptyStringInItems = (item) => item.items?.filter((v) => v.itemId);
const finalItems = myItems.map(removeEmptyStringInItems);
output.
{itemId : 'new', name : 'new name'}
Any ideas for this problem? I really need help!
you could try update the code to this to keep the finalItems format same as the initial value
const removeEmptyStringInItems = (items = []) => items?.filter((v) => v.itemId);
const finalItems = myItems.map((v) => ({...v, items: removeEmptyStringInItems(v.items)}));

How to map data depending on whether I ever get different objects? JS Angular 2+

I need to filter through, but the problem is that the knowledge I get changes its properties
First example of object ( of arrays )
{ name : 'test' , value: 'Values 1' },
{ name :'test 2' , value: 'Values 2' }
And when i filter this is easy:
<span *ngFor="let date of dates">
{{ date.value }}
</span>
But second time i got different data
{ name : 'test' , value: 'Values 1' },
{ name :'test 2' , value: 'Values 2' }
{ name :'test 3' , value: [{name :'test 3' , value: 'Values 3'}] },
{ name :'test 4' , value: [{name :'test 4' , value: 'Values 4'}] }
I need to filter this data and show only value ( last value )
the menu is currently displayed result example:
Values 1 , Values 2, [Object Object] , [Object Object]
You could NgIf and check if date.value is typeof array, if yes and its only 1 object, then make it display {{date.value.value}} else if its not an array display {{date.value}} ... sorry I can't type specifics
You can use map to modify the array of objects as per your need.
dates.map(x=>{
if(Array.isArray(x.value))
x.value = x.value[0].value
return x;
});
The result will be
[{ name : 'test' , value: 'Values 1' },
{ name :'test 2' , value: 'Values 2' }
{ name :'test 3' , value: 'Values 3'},
{ name :'test 4' , value: 'Values 4' }]
Update: if you want to print all the values, you can join them using map function, this will work for n objects inside value array.
dates.map(filerVal => {
if (Array.isArray(filerVal.value)){
filerVal.value = filerVal.value.map(v=>v.value).join(' ');
}
return filerVal;
});
stackblitz link.
let me know if this is what you expect.

Mongoose query returning more than one result

My database structure is looking like this :
{
'name' : 'entry one'
'project' :
[
{companyName : 'a name', contactPerson : [{ work_email: 'test#test.com'}] } ,
{companyName : 'a name1', contactPerson : [{ work_email: 'test1#test.com'}] } ,
{companyName : 'a name2', contactPerson : [{ work_email: 'test2#test.com'}] }
]
}
{
'name' : 'entry 2'
'project' :
[
{companyName : 'another name', contactPerson : [{ work_email: 'testing#test.com'}] } ,
{companyName : 'another name1', contactPerson : [{ work_email: 'testing1#test.com'}] } ,
{companyName : 'another name 2', contactPerson : [{ work_email: 'testing2#test.com'}] }
]
}
What i want is to find the companyName that belongs to a given work_email. So if the work_email is test#test.com the company name that should be returned should be 'a name'
So the query i built with mongoose is this :
const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test#test.nl'} , 'project.companyName');
But this is returning all company names (from entry one) not the single one i am looking for.
Filtering will always return whole document. You need to use projection to "reshape" it. You can consider the $ (projection) operator:
const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test#test.nl'} , { 'project.$': 1 });
Mongo Playground

Encountered two children with the same key, `[object Object]`

I am getting the following error : Encountered two children with the same key, [object Object]
I have the following array called cities :
[
{ 'city' : `AIRDRIE`, 'province' : 'AB' },
{ 'city' : `ALBERTA BEACH`, 'province' : 'AB' },
{ 'city' : `ATHABASCA`, 'province' : 'AB' },
{ 'city' : `BANFF`, 'province' : 'AB' },
{ 'city' : `BARRHEAD`, 'province' : 'AB' },
{ 'city' : `BEAUMONT`, 'province' : 'AB' },
{ 'city' : `BLACKFALDS`, 'province' : 'AB' },
...
]
Now I want to filter the array :
const optionsCity = cities.filter(( {province} ) => {
return province === this.state.province
})
which works fine until I try to open my dropdown.. I get error : Encountered two children with the same key, [object Object]
My dropdown is react-dropdown, here is the code :
<Dropdown
options={optionsCity}
onChange={this.updateCity.bind(this)}
value={this.state.city}
placeholder="Select a City" />
Here is my updateCity
updateCity(city) {
this.setState({city: city.name})
}
Anyone knows how to fix ?
I am sorry my English is very bad
Thanks !!
Based on https://github.com/fraserxu/react-dropdown, if you are using an object array of options, you need it to be in a particular format with keys - 'value' and 'label'
{ value: 'one', label: 'One' }
The filter returns an array of objects and not just an array of city names.
You will need to create a new objects array with the above keys or just use a flat array of city names

How to get the selected value from Kendo UI grid

I am using Kendo grid. I want to get the value(field-nlv_id) for the multiple row selected if select the rows. Also i want to get the number of selected rows and pass to the controller. Let me know the way to do it.
columns : [
{
'field' : 'nlv_id',
'title' : 'Asset ID'
},
{
'field' : 'due_date',
'title' : 'Partner Due Date'
},
{
'field' : 'link',
'title' : 'Partner'
},
{
'field' : 'playlist_type',
'title' : 'Playlist Style'
},
{
'field' : 'show_code',
'title' : 'Show Code'
},
{
'field' : 'status',
'title' : 'Status'
},
{
'field' : 'retry_count',
'title' : '# Retries'
}
],
scrollable : false,
pageable : {
pageSizes : [ 10, 25, 50 ],
buttonCount : 5,
refresh : true,
messages : {
display : "{0} - {1} of {2} assets",
itemsPerPage : "assets per page",
empty : "No assets to display"
}
},
dataSource : new kendo.data.DataSource({
serverPaging : true,
transport : {
read : getJobs
},
pageSize : 10,
schema : {
total : returnTotalCount
}
}),
selectable : 'multiple',
sortable : true
};
You will need to do an change() event on grid, then you will have selected items, for convinience i did an example using an list with all selected items, so you can easily get numbers of rows selected.
change: function (e, args) {
var currentSelected = this.select();
var dataSource = $grid.dataSource.data();
currentItems = [];
$.map(currentSelected, function (item) {
currentItems.push($grid.dataItem(item).nlv_id) ;
return $grid.dataItem(item).nlv_id;
});
alert(currentItems);
},
You can get count like that
currentItems.length;
EDIT: For convinience i create an example to do, is easier.
Important: you must set you 'nlv_id' in Schema!
http://jsfiddle.net/2ojwwpLf/
hope this help

Categories