I have two different array objects and have a function which uses the objects and performs calculations. I would like to know how to perform calculations and get all the nested array objects in JavaScript as shown below (expected output).
var obj = [
{
name: "insta",
fee: "2",
rate: "2.00"
},
{
name: "transfer",
fee: "1",
rate: "3.00"
}
],
var query =
{
country: "SG",
sourceamount: "4,000"
}
function config(objectdata, querydata){
let send_amount = querydata.sourceamount.replace(/,/g,"");
let fee = objectdata.fee;
let rate = objectdata.rate;
let amount_to_convert = send_amount - fee;
let receive_amount = amount_to_convert * rate;
let result_data = {send: send_amount, fees: fee, ratevalue: rate, amountvalue :amount_to_convert, receive: receive_amount}
return result_data;
}
result = config(obj, query);
Expected Output:
result = [
{
name: "insta",
fees: "2",
ratevalue: "2.00",
amountvalue: "3998",
receive: "7976"
country: "SG",
sourceamount: "4,000"
},
{
name: "transfer",
fees: "1",
ratevalue: "3.00",
amountvalue: "3997",
receive: "11,991"
country: "SG",
sourceamount: "4,000"
}
]
You need to map through the obj
array and construct your output.
NOTE: You need to parse the fee-rate-sourceamount
values if you want to perform arithmetic operations.
var obj = [{
name: "insta",
fee: "2",
rate: "2.00"
}, {
name: "transfer",
fee: "1",
rate: "3.00"
}];
var query = {
country: "SG",
sourceamount: "4,000"
};
function config(objectdata, querydata) {
let result_data = objectdata.map(function(obj) {
let send_amount = parseInt(querydata.sourceamount.replace(/,/g, ""));
let fee = parseInt(obj.fee);
let rate = parseInt(obj.rate);
let amount_to_convert = send_amount - fee;
let receive_amount = amount_to_convert * rate;
return {
name: obj.name,
fees: fee,
ratevalue: rate,
amountvalue: amount_to_convert,
receive: receive_amount,
country: querydata.country,
sourceamount: send_amount,
}
});
return result_data;
}
console.log(config(obj, query));
You can use .map to loop your array and construct all your object.
var obj = [{
name: "insta",
fee: "2",
rate: "2.00"
},
{
name: "transfer",
fee: "1",
rate: "3.00"
}
];
var query = {
country: "SG",
sourceamount: "4,000"
}
function config(objectdata, querydata) {
return objectdata.map(function(obj) {
let send_amount = +querydata.sourceamount.replace(/,/g, "");
let fee = +obj.fee;
let rate = +obj.rate;
let amount_to_convert = send_amount - fee;
let receive_amount = amount_to_convert * rate;
return {
name: obj.name,
fees: fee,
ratevalue: rate,
amountvalue: amount_to_convert,
receive: receive_amount,
...querydata
}
});
}
result = config(obj, query);
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With