Lodash group by multiple keys - lodash

I have following object
[{ Venue: 'NY',
Title: 'NY Feast',
PromoDate: '5/1/18',
EndDate: '5/1/18',
Price : $49.99,
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': '' },
{ Venue: 'NY',
Title: 'NY Flash',
PromoDate: '5/1/18',
EndDate: '5/1/18',
Price : $40.99,
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': '' },
{ Venue: 'BOSTON',
Title: 'Never Too Late',
PromoDate: '5/1/18',
EndDate: '5/1/18',
Price : $9.99,
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': '' },
{ Venue: 'BOSTON',
Title: 'The Reluctant Bride',
PromoDate: '5/1/18',
EndDate: '5/1/18',
Price : $19.99,
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': ''
}
]
Expected output after performing operation is
[{ Venue: 'NY',
Titles: [{Title: 'NY Feast', Price: '49.99'}, {Title:'NY Flash', Price: '$40.99'}],
PromoDate: '5/1/18',
EndDate: '5/1/18',
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': '' },
{ Venue: 'BOSTON',
Titles: [{Title: 'Never Too Late', Price: '$9.99'}, {Title: 'The Reluctant Bride', Price: '$19.99'}] ,
PromoDate: '5/1/18',
EndDate: '5/1/18',
Notes: '',
'Image Assigned': '',
'Image Ready': '',
'Ad Scheduled': '' }
]
I am trying with Lodash groupby but it isn't working for me. I have to group by title, PromoDate and EndDate as those are unique field.
I will appreciate any help on it.

You can do this with a single Array.reduce and without lodash:
let data = [{ Venue: 'NY', Title: 'NY Feast', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$49.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'NY', Title: 'NY Flash', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$40.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'BOSTON', Title: 'Never Too Late', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$9.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'BOSTON', Title: 'The Reluctant Bride', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$19.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' } ]
let result = data.reduce((r, c) => {
let key = `${c.Venue}-${c.PromoDate}-${c.EndDate}`
let { Title, Price, ...other } = c
r[key] = r[key] || { Titles: [], ...other }
r[key].Titles.push({ Title, Price })
return r
}, {})
console.log(Object.values(result))
The idea is to group on the composite key and then just reduce to the properties you need.

Related

Invalid property value: API create Mutation Sanity.io Reference is string - how to define as reference?

i am building a ecommerce site.
I have trouble adding orderItems to the Array in the Order-Document.
As you can see i am trying to reference the customer-Document and Product-Dokument in my orderItem. i am Posting in an array of objects that looks like:
[
{
productId: '5b79b3f8-6ef8-4c6d-bd85-5dcb14fb836d',
kundenId: 'c3777230-74cd-411b-a455-7fa905c90957',
quant: 1,
name: 'Position 1'
}
]
Can someone help me how i get sanity to understand the strings as _ref ?
My schemas are as follows:
export default {
title: 'Order Item',
name: 'orderItem',
type: 'object',
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
},
{
name: 'kundenId',
title: 'Customer',
type: 'reference',
to: [{ type: 'customer' }],
options: {
disableNew: true,
},
},
{
name: 'productId',
title: 'Product',
type: 'reference',
to: [{ type: 'product' }],
options: {
disableNew: true,
},
},
{
title: 'Quantity',
name: 'quant',
type: 'number',
},
{
title: 'Price',
name: 'price',
type: 'number',
},
],
};
and:
export default {
name: 'order',
title: 'Order',
type: 'document',
fields: [
{
name: 'user',
title: 'User',
type: 'reference',
to: [{ type: 'user' }],
options: {
disableNew: true,
},
},
{
name: 'userName',
title: 'User Name',
type: 'string',
},
{
title: 'Order Items',
name: 'orderItems',
type: 'array',
of: [
{
title: 'Order Item',
type: 'orderItem',
},
],
},
{
title: 'CreatedAt',
name: 'createdAt',
type: 'datetime',
},
],
};
so i solved this by using JSON.parse like so:
productId: JSON.parse(`{"_ref":"${artikel._id}"}`),
Good luck to everyone with the same issue.

ejs print value of array from specific id

I send an array of object called gudangs from my controller app.js like this
res.render('daftar-staff', {
title: 'Daftar Staff',
session: req.session,
layout: 'layouts/main-layouts',
gudangs
})
Its successfully sent to the ejs view and I received
{ _id: new ObjectId("61a804c4059d1d90797c8ad0"), nama: 'gudang benowo', alamat: '', __v: 0 },{ _id: new ObjectId("61a804ecdfa6962a0162850f"), nama: 'gudang pakal', alamat: '', __v: 0 },{ _id: new ObjectId("61a86fb98b3cd7f948a388b7"), nama: 'gudang tandes', alamat: 'tandes no 19', isFull: 'true', __v: 0 },{ _id: new ObjectId("61a872c07cc01577ddf78b53"), nama: 'gudang kepatihan', alamat: '', isFull: 'true', __v: 0 },{ _id: new ObjectId("61a954eee3c45454070d4b10"), alamat: 'jalan benowo 13', __v: 0 },{ _id: new ObjectId("61a955954e757a01405e44b4"), alamat: 'jalan benowo 13', __v: 0 }
What i want is to print nama on specific gudang _id
Right now I can accomplish this by iterate through all gudangs array like this
<% gudangs.forEach((gudang,i) => { %>
<% if(gudang._id==='xxxx'){ %>
<%= gudang.nama %>
<% } %>
<% } %>
I wonder is there any simple way to do this?
Using JS array filters
<%= gudangs.filter(({ _id })=> {return _id === 'XXX'})[0]['nama'] %>
gudangs = [{ _id: "61a804c4059d1d90797c8ad0", nama: 'gudang benowo', alamat: '', __v: 0 },{ _id: "61a804ecdfa6962a0162850f", nama: 'gudang pakal', alamat: '', __v: 0 },{ _id: "61a86fb98b3cd7f948a388b7", nama: 'gudang tandes', alamat: 'tandes no 19', isFull: 'true', __v: 0 },{ _id: "61a872c07cc01577ddf78b53", nama: 'gudang kepatihan', alamat: '', isFull: 'true', __v: 0 },{ _id: "61a954eee3c45454070d4b10", alamat: 'jalan benowo 13', __v: 0 },{ _id: "61a955954e757a01405e44b4", alamat: 'jalan benowo 13', __v: 0 }];
console.log(gudangs.filter(({ _id })=> {return _id === '61a804ecdfa6962a0162850f'})[0]['nama']);
This is a working snippet. Remember that ObjectId is not defined in frontend Javascript.

Remove an item from array by id

data: function(){
return {
items: [
{ id: '1', name: 'Item 1', bool: false},
{ id: '2', name: 'Item 2', bool: false},
{ id: '3', name: 'Item 3', bool: false},
{ id: '4', name: 'Item 4', bool: false}
],
checkedItems: [],
};
},
methods:
{
select: function(event, index) {
if (!this.items[index].bool) {
this.checkedItems.splice(index, 1);
} else {
this.checkedItems.push(this.items[index]);
}
}
}
When I click on the div it copies the items data into checkedItems and sets bool to true.
Is it possible to target the item id and remove that specific one from checkedItems as the current splice is removing the wrong item based off the index.
Why not use an object instead of an array, something like this:
data: function(){
return {
items: [
{ id: '1', name: 'Item 1', bool: false},
{ id: '2', name: 'Item 2', bool: false},
{ id: '3', name: 'Item 3', bool: false},
{ id: '4', name: 'Item 4', bool: false}
],
checkedItemsObj: {},
};
},
methods:
{
select: function(event, index) {
let item = this.items[index];
if (!item.bool) {
this.checkedItemsObj[item.id] = item
} else {
delete this.checkedItemsObj[item.id]
}
},
getCheckedItems: () => Object.values(data().checkedItemsObj)
}
Now to get the array of checked items anytime, you can call methods.getCheckedItems()

React Native Filter data

I'm making a chat app with N participants, and want to search according to first name.
const filteredData = this.state.rawData.filter(id =>
id.members[0].first_name.toUpperCase().indexOf(event.toUpperCase()) !== -1
||
id.members[1].first_name.toUpperCase().indexOf(event.toUpperCase()) !== -1
)
is not acceptable, as there are n members, not always two.
const filteredData = this.state.rawData.filter(id =>
id.members.forEach(element => {
element.first_name.toUpperCase().indexOf(event.toUpperCase()) !== -1
}
)
Returns me that undefined is not an object 'element.first_name.toUpperCase'
Why?
EDIT:
Sample data
rawData: [
{
new: 0,
id: '1',
members:
[
{
email: 'grantmarshall#test.com',
first_name: 'Grant',
last_name: 'Marshall',
id: "1",
last_login_time: 10002,
phone_number: '1234665',
phone_number_international: '+1',
picture: '',
status:'',
username:'Grant Marshall',
user:'',
},
{
email: 'you#you.com',
first_name: 'youfn',
last_name: 'yousn',
id: "5ad0007828b1930043a5303d",
last_login_time: 10002,
phone_number: '1234665',
phone_number_international: '+1',
picture: '',
status:'',
username:'youfn youfn',
user:'',
},
{ email: 'self#self.com' }],
messages:
[
{ chat_id: 1, _id: "1", from: 'Grant Marshall', text: 'roident est duis duis sit occaecat ea eiusmod laboris mollit', time: '9:22', parse_mode: 'none' }
,
{ chat_id: 1, _id: "5ad0007828b1930043a5303d", from: 'Dave Pilkinton', text: 'Should not display', time: '9:22', parse_mode: 'none' },
{ chat_id: 1, _id: "1", from: 'Grant Marshall', text: 'my second', time: '9:22', parse_mode: 'none' }
,
{ chat_id: 1, _id: "5ad0007828b1930043a5303d", from: 'Dave Pilkinton', text: 'my second Should not display', time: '9:22', parse_mode: 'none' },
]
},
It's because element.first_name is undefined in 3rd iteration of the array.
Change your condition to:
element.first_name && element.first_name.toUpperCase().indexOf(event.toUpperCase()) !== -1

compare previous value in each loop with current value

i have a json that i have to itterate in my jade :
[
{ RefSlipNo:
{ fieldlabel: 'RefSlipNo',
fieldname: 'RefSlipNo',
fieldtype: 'text',
required: '1',
default_value: '',
placeholder: 'Ref Slip No',
order_no: '1',
formgroup: 'vehicleDetails',
can_delete: '0',
status: '1' },
BookNumber:
{ fieldlabel: 'BookNumber',
fieldname: 'BookNumber',
fieldtype: 'text',
required: '1',
default_value: '',
placeholder: 'Book Number',
order_no: '2',
formgroup: 'vehicleDetails',
can_delete: '1',
status: '1' },
SlipDate:
{ fieldlabel: 'SlipDate',
fieldname: 'SlipDate',
fieldtype: 'text',
required: '1',
default_value: '',
placeholder: 'Slip Date',
order_no: '3',
formgroup: 'invoice',
can_delete: '1',
status: '1' },
FillFuelDate:
{ fieldlabel: 'FillFuelDate',
fieldname: 'FillFuelDate',
fieldtype: 'text',
required: '1',
default_value: '',
placeholder: 'Fill Fuel Date',
order_no: '4',
formgroup: 'invoice',
can_delete: '1',
status: '1' }
]
i want to use fieldset and legend on the basis of formgroup like:
-------invoice--------------------|
FillFuelDate : |
SlipDate : |
----------------------------------|
-------vehicleDetails-------------|
RefSlipNo : |
BookNumber : |
----------------------------------|
But could not able to get logic. How to loop it in jade. I want to get all field list with invoice formgroup under one fieldset and all vehicledetails under 1 fieldset as shown above.
In your JavaScript, define a function like this, and pass it as a local to your pug template:
function groupByFormGroup(fields) {
const formGroups = [];
const formGroupsByName = {};
fields.forEach(field => {
if (!formGroupsByName[field.formGroup]) {
formGroupsByName[field.formGroup] = {name: field.formGroup, fields: []};
formGroups.push(formGroupsByName);
}
formGroupsByName[field.formGroup].push(field);
});
}
Then in the pug template, do something like:
each formGroup in groupByFormGroup(fields)
fieldset
legend= formGroup.name
each field in formGroup.fields
label= field.fieldLabel
input(type="text" name=field.fieldName)