I'm builing notifications component where I want to sort notification by dates and display them.
Can someone give me a hint to achieve that?
How can I do it over a following array ?
Array :
notificationRows: Array(25)
0:
notificationRow:
fee: "20 TEST"
id: "1.11.191431"
info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]"
key: "1.11.191431"
time: "2022-05-17 16:54:21"
type: "transfer"
[[Prototype]]: Object
unread: false
[[Prototype]]: Object
1:
notificationRow:
fee: "20 TEST"
id: "1.11.191430"
info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]"
key: "1.11.191430"
time: "2022-05-17 14:52:39"
type: "transfer"
[[Prototype]]: Object
unread: false
[[Prototype]]: Object
2:
notificationRow:
fee: "20 TEST"
id: "1.11.191427"
info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]"
key: "1.11.191427"
time: "2022-05-17 14:34:15"
type: "transfer"
[[Prototype]]: Object
unread: false
My expected result is :
Sort the array with descending dates, use sort() and getTime() for dates.
And in the return of your component, use map() to return an HTML element for each array item.
example using a function component
function App(props) {
const {arr} = props;
arr.sort((a, b) => {
const date1 = new Date(a.notificationRow.time);
const date2 = new Date(b.notificationRow.time);
return date2.getTime() - date1.getTime();
})
return (
{
arr.map((elem, i) => (<div key={i}>whatever you want here</div>))
}
)
}
you can use array.sort() function in JavaScript to sort by date.
const notificationRows = [
{
notificationRow: {
fee: "20 TEST",
id: "1.11.191431",
info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]",
key: "1.11.191431",
time: "2022-05-17 16:54:21",
type: "transfer",
unread: false
}
},
{
notificationRow: {
fee: "20 TEST",
id: "1.11.191430",
info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]",
key: "1.11.191430",
time: "2022-05-17 14:52:39",
type: "transfer",
unread: false
}
},
{
notificationRow: {
fee: "20 TEST",
id: "1.11.191427",
info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]",
key: "1.11.191427",
time: "2022-05-17 14:34:15",
type: "transfer",
unread: false
}
}
];
const sorted = constarr.sort(
(a, b) =>
// return sorted date by newest. if want sort by old use Date.parse(a.notificationRow.time) - Date.parse(b.notificationRow.time)
Date.parse(b.notificationRow.time) - Date.parse(a.notificationRow.time)
);
console.log("sorted", sorted);
Since you use react and you may use this sorted by time notifications to display, set this sorted arrays to the react state and render accordingly.
Related
I have multiple array in reactjs.
{last_name: 'User1', status: 'BRONZE', type: 'Maintenance', due_date: '2022-06-04 00:00:00'}
{last_name: 'User1', status: 'BRONZE', type: 'Contrôle technique', due_date: '2022-06-18 00:00:00'}
{last_name: 'User2', status: 'BRONZE', type: 'Unknow', due_date: null}
I would like to merge the array by user last_name to have a result like this:
{last_name: 'User1', status1: 'BRONZE', type: 'Maintenance1', due_date1: '2022-06-04 00:00:00', status2: 'BRONZE', type2: 'Contrôle technique', due_date: '2022-06-18 00:00:00'}
{last_name: 'User2', status: 'BRONZE', type: 'Unknow', due_date: null}
In my example I have merge the array 1 and 2 to have 1 array "group by" last_name, here User1 but I need to keep the value of the second array too.
Your question lacks a few details. Are status and due_date the only fields that might be repeated? If so, the below answer should work. If not, you might want to specify which keys should be merged with an index in the field name, and which can be pulled in as is.
I'm not sure why you would want to structure your data this way-- having different field names seems like it would make it difficult to find the data, but leaving that aside:
const data = [{
last_name: 'User1',
status: 'BRONZE',
type: 'Maintenance',
due_date: '2022-06-04 00:00:00'
}, {
last_name: 'User1',
status: 'BRONZE',
type: 'Contrôle technique',
due_date: '2022-06-18 00:00:00'
}, {
last_name: 'User2',
status: 'BRONZE',
type: 'Unknow',
due_date: null
}]
const mergedMap = {}
// Group list elements by last_name
for (const el of data) {
if (el.last_name in mergedMap) {
mergedMap[el.last_name].push(el)
} else {
mergedMap[el.last_name] = [el]
}
}
// Iterate over "user" groups, modifying field names.
const mergedList = []
for (const last_name in mergedMap) {
const elCount = mergedMap[last_name].length
// If there's only one entry for this "last_name", keep it as is,
// then continue to next user.
if (elCount === 1){
mergedList.push(mergedMap[last_name][0])
continue
}
const mergedUser = mergedMap[last_name].reduce((merged, el, index) => ({
// Keep whatever keys are already here
...merged,
// last_name and status are assumed to always be the same
// for a given user, so they're safe to overwrite each time
last_name: el.last_name,
status: el.status,
// type and due_date might be unique for each entry, so
// we add an index to the field name and copy the new value in
[`type${index + 1}`]: el.type,
[`due_date${index + 1}`]: el.due_date,
}), {})
mergedList.push(mergedUser)
}
console.log(JSON.stringify(mergedList, null, 2))
I am trying object validation with the help of joi.
I want to validate object as a constraint inside an object like
let login = {
value: 0/1,
slots: [{ label: '', value: '24 hr'}, { label: '', value: '24 hr'}]
}
Here login is an object and inside it slots is also an object. So if I write like the following
const schema = Joi.object().keys({
value : Joi.number.required(),
slots : Joi.string.required()
});
would it be correct for object data type or should I replace string data type with object data type?
I want to validate object type as a constraint.
Your slots key needs to be an array of objects:
const schema = Joi.object().keys({
value: Joi.number().required(),
slots: Joi.array().items(
Joi.object().keys({
label: Joi.string().required().allow(''),
value: Joi.string().required()
})
)
})
This way, the following object will be valid:
const obj = {
value: 1,
slots: [
{
label: '',
value: '24 hr'
}
]
}
I am building a search functionality with multiple search criteria.
Is there any way we could dynamically generate single line of chainable filters including custom methods.
Data:
SN
EventDate
Activity
Devices
Description
1
12/12/20
Sports
Fitbit
Archived rewards via running
2
13/12/20
Sports
Apple
Achieved rewards via running
3
14/12/20
Purchase
NA
Purchased coins for purchase
4
14/12/20
Sports
Fitbit
Archived rewards via running
5
16/12/20
Sports
Fitbit
Archived rewards via running
from below filter condition I am expecting
SN
EventDate
Activity
Devices
Description
1
12/12/20
Sports
Fitbit
Archived rewards via running
2
13/12/20
Sports
Apple
Achieved rewards via running
4
14/12/20
Sports
Fitbit
Archived rewards via running
Input Filter Condition:
const input = [
{
Field: 'Activity',
Operation: 'EQUALS',
Values: 'Sports'
},
{
Field: 'EventDate',
Operation: 'DATEBETWEEN',
Values: {startDate:2020-12-12, endDate: 2020-12-15}
},
{
Field: 'Devices',
Operation: 'INCLUDES'
Values: {Fitbit,Apple}
},
{
Field: 'All', // if ALL then all fields else array of fields
Operation: 'GLOBAL',
Values: 'Run'//keyword to search
}
];
Something like below
global(objects, keyword) {
retturn objects.filter(object => Object.values(object).some(i => i.includes(keyword)));
}
const filteredList = FilterModule
.include(field, array)
.equals(field, value)
.equals(field, value)
.global(field, array);
Need to generate dynamic filter modules based on input filter condition all the condition's are 'AND' condition.
only via JavaScript
You could create functions with a closure over the key/value and expect the object for checking.
DATEBETWEEN expects dates in ISO 8601 format.
const
data = [{ SN: 1, EventDate: '2020-12-12', Activity: 'Sports', Devices: 'Fitbit', Description: 'Archived rewards via running' }, { SN: 2, EventDate: '2020-12-13', Activity: 'Sports', Devices: 'Apple', Description: 'Achieved rewards via running' }, { SN: 3, EventDate: '2020-12-14', Activity: 'Purchase', Devices: 'NA', Description: 'Purchased coins for purchase' }, { SN: 4, EventDate: '2020-12-14', Activity: 'Sports', Devices: 'Fitbit', Description: 'Archived rewards via running' }, { SN: 5, EventDate: '2020-12-16', Activity: 'Sports', Devices: 'Fitbit', Description: 'Archived rewards via running' }],
input = [
{ Field: 'Activity', Operation: 'EQUALS', Values: 'Sports' },
{ Field: 'EventDate', Operation: 'DATEBETWEEN', Values: { startDate: '2020-12-12', endDate: '2020-12-15' } },
{ Field: 'Devices', Operation: 'INCLUDES', Values: ['Fitbit', 'Apple'] },
{ Field: 'All', Operation: 'GLOBAL', Values: 'Run' }
],
operators = {
EQUALS(k, v) { return o => o[k] === v; },
DATEBETWEEN(k, v) { return o => o[k] >= v.startDate && o[k] <= v.endDate; },
INCLUDES(k, v) { return o => v.includes(o[k]); },
GLOBAL(k, v) { v = v.toLowerCase(); return o => Object.values(o).some(s => s.toString().toLowerCase().includes(v)); }
},
filters = input.map(({ Field, Operation, Values }) => operators[Operation](Field, Values)),
result = data.filter(o => filters.every(f => f(o)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am reading a list that has the following structure:
export interface ISaleEntity {
id: number;
dateCreated: Date,
amount:number,
type:string,
description:string
}
My api is returning the following data:
payments: Array(2) 0: {Id: 1, Type: "DEBIT", Description: "Sale
1", Amount: 5000, DateCreated: "06/18/2018 00:00:00"} 1: {Id: 2, Type:
"CREDIT", Description: "Sale1", Amount: 4200, DateCreated: "06/20/2018
00:00:00"}
Since I am using transcript, I do
const payments: ISaleEntity [] = response.data.payments;
private renderData(payments: ISaleEntity[]) {
return (
<div>
{payments.length}
{payments.forEach(element =>
// tslint:disable-next-line:no-console
console.log("element" + element)
// <span>{element.description}</span>
)}
</div>
);
}
In console, element is [object Object].
How can I read the loop through JSON object properties?
var elements=[{Id: 1, Type: "DEBIT", Description: "Sale 1", Amount: 5000, DateCreated: "06/18/2018 00:00:00"} ,{Id: 2, Type: "CREDIT", Description: "Sale1", Amount: 4200, DateCreated: "06/20/2018 00:00:00"}]
elements.forEach(function(elem){
console.log(elem);
console.log(elem.Description)
})
console.log(elements[0].Description)
If you want to concatenate with string just use
console.log("element" + JSON.stringify(element)).
+ element coerces the object element into a string, which is just [object Object]
console.log is an overloaded function that accepts a list of parameters that are either passed by copy (string|number|boolean) or by reference (everything else).
Just pass it as another argument to console.log:
console.log("element", element);
I am trying to update my redux crud form.I am using with the help of immutatbility helper.
My reducer is:
case UPDATE_TODO:
console.log("reducer todo",action.toDo,state)
return update(state, { $set: [action.toDo] })
But instead of replacing specific object it replace whole array into one.Where I am doing wrong??
My State is this:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
and after updating it should be like this:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
but instead its giving result this:
[
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
Your code is not targeting the specific todo you want to update in state, hence it replaces the whole state. There are two ways you can achieve this:
1) Find the index of the todo item you want to update using Array.findIndex method before using $set method.
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {[todoIndex]: {$set: action.todDo }})
2) Find the index of the todo item you want as (1) above and then use $splice method.
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {$splice: [[todoIndex,1,action.todDo]]})