How do I get all objects in a nested array after performing a calculation in JavaScript?
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)
const array = [{
name: "insta",
fee: "2",
rate: "2.00"
}, {
name: "transfer",
fee: "1",
rate: "3.00"
}]
const query = { country: "SG", sourceamount: "4,000" }
function config (data, querydata) {
const send_amount = querydata.sourceamount.replace(/,/g,"")
return data.map(({ fee, rate, ...rest }) => ({
fees: fee,
ratevalue: rate,
amountvalue: +send_amount - +fee,
receive: (+send_amount - +fee) * +rate,
...rest,
...querydata
}))
}
result = config(array, query)
console.log(result)