How to read through [object Object]? - javascript

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);

Related

Best way to return a nested object the matches a property requested

I'm trying to create a new object that only contains the a product array with the seller I req. I have an order object that has a product array. I'd like to return a specific seller. I tried:
const newOrders = orders.map((element) => {
return {
...element,
product: element.product.filter(
(seller) => seller === req.currentUser!.id
),
};
});
does mongoose have a preferred method for doing what I bring to achieve? I've read through the find queries but none of the methods seem useful to this use case.
orders: [
{
userId: "638795ad742ef7a17e258693",
status: "pending",
shippingInfo: {
line1: "599 East Liberty Street",
line2: null,
city: "Toronto",
country: "CA",
postal_code: "M7K 8P3",
state: "MT"
},
product: [
{
title: "new image",
description: "a log description",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "63737e4b0adf387c5e863d33"
},
{
title: "Mekks",
description: "Ple",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "6376706808cf1adafd5af32f"
},
{
title: "Meeks Prodyuct",
description: "long description",
seller: "63868795a6196afbc3677cfe",
__v: 1,
id: "63868812a6196afbc3677d06"
}
],
version: 1,
id: "6388138170892249e01bdcba"
}
],
Im sure this can be improved, doesn't feel that its the best way possible but it gets the result. Like the previous answer you have to find first the order the seller is in then find the products than filter the seller by the id. I'm using typescript and there's a bug https://github.com/microsoft/TypeScript/issues/50769 so you have to use the bracket notation.
const orders = await Order.find({
"product.seller": req.currentUser!.id,
});
const allOrders = orders[0].product;
const sellerOrders = allOrders.filter((obj) => {
return obj["seller"] === req.currentUser!.id;
});

How to achive below result using provided array?

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.

Typescript: Property 'name' does not exist on type 'Employee[]'

I am completely new to typescript, and I'm stumped by this error message: Property 'name' does not exist on type 'Employee[]' Could someone please point out where I'm not applying the "name" type within the Employee array? Thanks.
interface Employee {
id: number;
name: string;
title: string;
}
var employees: Employee[] = [
{ id: 0, name: "Franklin", title: "Software Enginner" },
{ id: 1, name: "Jamie", title: "Human Resources" },
{ id: 2, name: "Henry", title: "Application Designer" },
{ id: 3, name: "Lauren" title: "Software Enginner" },
{ id: 4, name: "Daniel" title: "Software Enginner 2" },
];
function fetchEmployeeName(id : number) {
var employee = employees.filter(
(employee) => employee.id === id
);
// The error occurs when I try to return a "name" under an employee that matched by id.
return employee.name;
}
console.log("Got Employee: "), fetchEmployeeName(3));
filter returns a new array containing all matching items:
[1, 2, 3].filter(i => i === 4)
The above will return an empty array.
What you want to use is find, which will return a single matching item or undefined.
Modify the fetchEmployeeName function to use find:
function fetchEmployeeName(id : number): string | null {
var employee = employees.find(
(employee) => employee.id === id
);
if (employee === undefined) return null;
return employee.name;
}
Try using find instead of filter. Filter returns an array. Find returns a single object. Next time, if using vscode, hover over employee on the first line of fetchEmployeeName, and check its type. Intellisense in vscode will point out to you that employee is clearly an array.
I highly recommend you to use find instead of filter, but if you really want to stick to your approach, you will have to access the only member in the employees array though its index (filter returns an array filled with the elements that meet the specified condition). E.G.:
return employee[0].name
Again, you can solve this particular issue by using filter, since it returns a single element you access without the need of an index (this will allow you to leave the return statement as it is).
there you have it, so what happened, your filter is returning to a new "Employee" that is not defined as an object,my advise is to always try to use pure functions and understand what your return is
interface Employee {
id: number;
name: string;
title: string;
}
var employees: Employee[] = [
{ id: 0, name: "Franklin", title: "Software Enginner" },
{ id: 1, name: "Jamie", title: "Human Resources" },
{ id: 2, name: "Henry", title: "Application Designer" },
{ id: 3, name: "Lauren", title: "Software Enginner" },
{ id: 4, name: "Daniel", title: "Software Enginner 2" },
];
function fetchEmployeeName (id:number, employees: Employee[]){
let employee = null
for (let i = 0, j = employees.length ; i < j; i++) {
if (employees[i].id === id) {
employee = employees[i].name
}
}
return employee
}
console.log(`Got employee 3: ${fetchEmployeeName(3,employees)}`);

How can I merge an array and group by key in Javascript?

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))

Issue finding mongoose ObjectID in array of strings representing ObjectIDs

I need to find the index of the mongoose objectID in an array like this:
[ { _id: 58676b0a27b3782b92066ab6, score: 0 },
{ _id: 58676aca27b3782b92066ab4, score: 3 },
{ _id: 58676aef27b3782b92066ab5, score: 0 }]
The model I am using to compare is a mongoose schema with the following data:
{_id: 5868d41d27b3782b92066ac5,
updatedAt: 2017-01-01T21:38:30.070Z,
createdAt: 2017-01-01T10:04:13.413Z,
recurrence: 'once only',
end: 2017-01-02T00:00:00.000Z,
title: 'Go to bed without fuss / coming down',
_user: 58676aca27b3782b92066ab4,
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false }
I am trying to find the index of the model._user in the array above using the following:
var isIndex = individualScores.map(function(is) {return is._id; }).indexOf(taskList[i]._user);
Where individualScores is the original array and taskList[i] is the task model. However, this always returns -1. It never finds the correct _id in the array.
I guess your problem is related to how _id are returned by your query
If you get _id as String, your code should work, check the snippet below
But if instead, you get ObjectsIds, you have to cast them to String first
var individualScores = [
{ _id: "58676b0a27b3782b92066ab6", score: 0 },
{ _id: "58676aca27b3782b92066ab4", score: 3 },
{ _id: "58676aef27b3782b92066ab5", score: 0 }
]
var task = {
_id: "5868d41d27b3782b92066ac5",
updatedAt: new Date("2017-01-01T21:38:30.070Z"),
createdAt: new Date("2017-01-01T10:04:13.413Z"),
recurrence: 'once only',
end: new Date("2017-01-02T00:00:00.000Z"),
title: 'Go to bed without fuss / coming down',
_user: "58676aca27b3782b92066ab4",
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false
}
var isIndex = individualScores.map(
function(is) {
return is._id;
})
.indexOf(task._user);
console.log(isIndex)
I think your process should working well that you are using just only need to convert 'objectID' to String to compare. Convert using .toString() for both of _id and _user.
like bellow:
var isIndex = individualScores.map(function(is) {
return is._id.toString();
}).indexOf(taskList[i]._user.toString());

Categories