from client side I am passing this items array
{ id: '1', quantity: '1' }
{ id: '2', quantity: '1' }
like shown below
# Javascript
fetch("/purchase", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
items: items,
}),
})
In the server side I access the item.id which is passed from the client side and map the corresponding value in the storeItems array but here I am getting undefined.
# Nodejs
const storeItems = new Map([
[1, { price: 10000, name: "Assessment" }],
[2, { price: 20000, name: "Therapy" }],
])
app.post("/purchase", (req, res) => {
req.body.items.forEach(function(item){
console.log(item.id) //this works
const storeItem = storeItems.get(item.id)
console.log(storeItem) //getting undefined
})
})
That's because item.id holds a string and passing e.g. "1" to the get method will result in undefined as the map's keys are of type Number. To fix this you can either convert the string to a number or store the item-ids as a string instead of a number:
const storeItem = storeItems.get(Number.parseInt(item.id));
OR
const storeItems = new Map([
["1", { price: 10000, name: "Assessment" }],
["2", { price: 20000, name: "Therapy" }],
])
in your client side you are passing id of items as string
{ id: '1', quantity: '1' }
{ id: '2', quantity: '1' }
but in node.js map you define map as integer
const storeItems = new Map([
[1, { price: 10000, name: "Assessment" }],
[2, { price: 20000, name: "Therapy" }],
])
there are some solution ,
convert id to interger in
const storeItem = storeItems.get(item.id)
and convert item.id to Integer
const storeItem = storeItems.get(parseInt(item.id))
and final result of your node js will be like this :
# Nodejs
const storeItems = new Map([
[1, { price: 10000, name: "Assessment" }],
[2, { price: 20000, name: "Therapy" }],
])
app.post("/purchase", (req, res) => {
req.body.items.forEach(function(item){
console.log(item.id) //this works
const storeItem = storeItems.get(parseInt(item.id)) //// change this line
console.log(storeItem) //getting undefined
})
})