I am working on nodejs. How to sum of amount which has the dictionary key value of Senior from the list dictionary?
traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
];
expected result = {"senior": 100, "Adult":75}
You can use a reduce function like the following:
traveler.reduce((prevValue, t) => {
return Object.assign(prevValue, { [t.description]: (prevValue[t.description] || 0) + t.Amount })
}, {});
Read about reduce function here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Related
I have the following code it suppose to send the data to pay pal to process the payment but it keepsgeting this TypeError: Cannot read property 'price' of undefined i have gone through the code but i think the error is occuring "storeItems.get(item.id).price" when i try to get the "items id" for some reson thwe value is nt being seen
this is my request body contains the following array
{"items":[
{"id":"1", "quantity":1},
{"id":"2", "quantity":2},
{"id":"3", "quantity":3},
{"id":"4", "quantity":4}
]}
app.post("/create-order", async (req, res) => {
const request = new paypal.orders.OrdersCreateRequest()
const total = req.body.items.reduce((sum, item) => {
return sum + storeItems.get(item.id).price * item.quantity
}, 0)
console.log(total);
request.prefer("return=representation")
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: total,
breakdown: {
item_total: {
currency_code: "USD",
value: total,
},
},
},
items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
name: storeItem.name,
unit_amount: {
currency_code: "USD",
value: storeItem.price,
},
quantity: item.quantity,
}
}),
},
],
})
const order = await paypalClient.execute(request)
})
The error means that storeItems.get(item.id) in the total function is undefined.
From your comment, storeItems is defined like:
const storeItems = new Map([
[1, { price: 100, name: "Learn React Today" }],
[2, { price: 200, name: "Learn CSS Today" }],
])
So the issue must come from the item. Either it does not have an id property, or it is undefined, or its id property does not match any entry in your map.
I am trying to find the total from objects inside an array, which each object has a price and quantity,
i can find the total when the array has exactly two objects, but for more than two it produces NaN.
arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]
const reducer = (accumulator, currentValue) => {
var a = accumulator.quantity * accumulator.price;
var b = currentValue.quantity * currentValue.price;
return a + b;
}
console.log(arr.reduce(reducer)); // sum if array contains 2 objects, NaN otherwise.
let arr = [
{ quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 }
]
let reducer = (acc, cur) => {
return acc + (Number(cur.quantity) * Number(cur.price));
};
console.log(arr.reduce(reducer, 0));
// 100
Your reducer function seems to be wrong. Accumulator no longer has any parameters to it, since well, it accumulates - its an integer.
Also, set a initial value for your accumulator to start accumulating from, as shown in the reduce function, second parameter input
arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]
const reducer = (accumulator, currentValue) {
return accumulator + (currentValue.quantity * accumulator.price);
}
console.log(arr.reduce(reducer, 0 ));
you can simply say
arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]
const total = arr.reduce((total,item)=>{
total += item.quantity * item.price;
return total
},0)
I retrieved the object type data from the firestore and stored in a variable document
{ Invite1: { Amount: 25, PhoneNumber: 917995954482 },
Invite2: { Amount: 25, PhoneNumber: 918179405940 },
Invite3: { Amount: 25, PhoneNumber: 918179441493 },
Invite4: { Amount: 25, PhoneNumber: 918309097608 } }
Now, I need to get the PhoneNumber from all the Invite.
After getting all the phone numbers into an array I need to check these Phone numbers already exists in database path like
/deyaPayUsers // collection
{authid} //document
Name: abcd
Phone Number: 987654321
Just try this :)
var phoneNumbers = [];
var data = { Invite1: { Amount: 25, PhoneNumber: 917995954482 },
Invite2: { Amount: 25, PhoneNumber: 918179405940 },
Invite3: { Amount: 25, PhoneNumber: 918179441493 },
Invite4: { Amount: 25, PhoneNumber: 918309097608 } }
for(var k in data){
phoneNumbers.push(data[k].PhoneNumber);
}
Try
var phoneNumbers = Object.keys(document).map(item => document[item].PhoneNumber);
Edited to take document as an object instead of array.
I used this as reference but this only shows the first value found but i want all the possible values to be printed.
var inventory = [{ name: 'apples', quantity: 2 }, { name: 'bananas', quantity: 0 }, { name: 'cherries', quantity: 5 }, { name: 'cherries', quantity: 8 }];
function findCherries(fruit) { return fruit.name === 'cherries'; }
console.log(inventory.filter(findCherries));
the filter function is supposed to return you an array, so I'm guessing your problem is simply that the console.log function doesn't display all of it. Try console.log(inventory.filter(findCherries).toString())
I am making a barcode scanner for my school project but i am stuck. I dont know how to scan through this object. I have this object with objects inside, and I need to scan through each object inside storage variable to check its barcode.
var storage = {
bolts: {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
brackets: {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
},
}
I have a variable called barcode, and I need to test this variable if its the same like one of these. I tried using
for (var key in storage){
if (storage[key].barcode === barcode){
}
}
I would like the most simple way to do that.
Use Object.keys:
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Below is the example:
var storage = {
"bolts": {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
"brackets": {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
}
}
var barcode = 57263144;
Object.keys(storage).forEach(function(key) {
if(storage[key].barcode === barcode) { console.log("do something")}
});
A Fiddle:
https://jsfiddle.net/spechackers/34bhthza/
Use the recursive function to verify if exist more nodes in the objects, example:
const complexObj = {
name: "nobody",
address: { number: 22, moreNumbers: [1,2,3,4,5] },
colors: ["green", "red"],
numbersAgain: { first: 1, second: 4 }
};
function scanObj(obj){
for (let i in obj) {
/*
*Do some verificatio, example:
*I'd like to verify all numbers and if the numbers is greater than 3:
*/
if(typeof obj[i] == "number" && obj[i] > 3){ console.log(obj[i]); }
if (typeof obj[i] === "object") {
scanObj(obj[i])
}
}
}
//call the method
scanObj(complexObj);
Output: 22 4 5 4