I am currently struggling with the formatting of a map operation on two object arrays in Javascript.
So lets say we have two arrays:
var customer = [
{ "Name": "Thomas", "Address": "example street 34", "customerID": 1 },
{ "Name": "Alica", "Address": "example street 24", "customerID": 2 },
{ "Name": "John", "Address": "example bouelvard 4", "customerID": 3 }
]
var orders = [
{ "Product": "iPhone 12", "Amount": 2, "customerID": 1 },
{ "Product": "charger", "Amount": 1, "customerID": 1 },
{ "Product": "screen protection", "Amount": 5, "customerID": 2 }
]
I want to have a result array so that when I print it out, I have an overview over customers with their orders in this way:
{
customer: {
"Name": "Thomas",
"Address": "example street 34",
"customerID": 1,
},
order: [
{
"Product": "iPhone 12",
"Amount": 2,
"customerID": 1
},
{
"Product": "charger",
"Amount": 1,
"customerID": 1
}
]
}
So I basically did a map function and searched for orders with the same customer id.
let overview = customers.map(element1 => ({ ...element1, : [...(orders.filter(element => element.customerID === element1.customerID))] }));
This is what I get:
{
"Name": "Thomas",
"Address": "example street 34",
"customerID": 1,
"order": [[Object], [Object]]
}
How do I get the "customer:" before the output of the customer objects and why do I get the Object output in my order array?
4
Answers
try with that:
You were missing ‘order’ key and also don’t need to spread since filter returns an array (empty if nothing filtered)
First you can create map from
orders
array wherecustomerId
will be key and array with all orders belonging to one customer will be map value.Next is initialising empty
results
array and iteratingcustomers
array. While iterating, push new object toresults
array. New object should contain 2 fields,customer
andorder
.customer
is object from iteration andorder
is map value which you get from previously generate map usingcustomer.customerID
as map key.This way, performance are increased because fetching data from Map data structure has O(1) time complexity. Using filter method to find all orders for specific customer is time consuming with complexity O(n).
You’re almost there:
You are so close! So very close. You can rename
customer
tocustomers
just to avoid confusion theelement1
becomescustomer
and the rest is as shown below: