I would like to calculate a new value based on two objects and add the result as new object to the existing array.
The input looks like:
[{
"trades": [
{
"fields": {
"orderOpenPrice": "1.40000",
"orderTakeProfit": "1.50000",
[...]
},
},
{
"fields": {
"orderOpenPrice": "1.30000",
"orderTargetPrice": "1.50000",
[...]
}
},
{
"fields": {
"orderOpenPrice": "1.50000",
"orderTargetPrice": "1.55000",
[...]
}
},
[...]
}]
This is the desired output:
[{
"trades": [
{
"fields": {
"orderOpenPrice": "1.40000",
"orderTakeProfit": "1.50000",
"pipsTargetedKey": "10000",
[...]
},
},
{
"fields": {
"orderOpenPrice": "1.30000",
"orderTakeProfit": "1.50000",
"pipsTargetedKey": "20000",
[...]
}
},
{
"fields": {
"orderOpenPrice": "1.50000",
"orderTakeProfit": "1.55000",
"pipsTargetedKey": "5000",
[...]
}
},
[...]
}]
I tried two different approaches using this thread: How can I add a key/value pair to a JavaScript object?:
Using assign
:
[...]
for (var i = 0; i < tradesTotal; i++) {
pipsTargeted = Math.abs(trades[i].fields.orderOpenPrice - trades[i].fields.orderTakeProfit);
trades[i].fields.assign(trades[i].fields, {pipsTargetedKey: pipsTargeted});
}
[...]
Using dot notation
:
[...]
for (var i = 0; i < tradesTotal; i++) {
pipsTargeted = Math.abs(trades[i].fields.orderOpenPrice - trades[i].fields.orderTakeProfit);
trades[i].fields.pipsTargetedKey = pipsTargeted
}
[...]
However, both attempts do not add another key:value pair.
Edit on request:
tradesTotal = Object.keys(trades).length;
// manipulate trades object
for (var i = 0; i < tradesTotal; i++) {
// format dateTime
trades[i].fields.orderOpenTime = (trades[i].fields.orderOpenTime).replace('T', ' ');
if (trades[i].fields.orderCloseTime !== null)
trades[i].fields.orderCloseTime = (trades[i].fields.orderCloseTime).replace('T', ' ');
// format orderType
if (trades[i].fields.orderType === 0) {
trades[i].fields.orderType = 'Buy'
} else if (trades[i].fields.orderType === 1) {
trades[i].fields.orderType = 'Sell'
} else if (trades[i].fields.orderType === 2) {
trades[i].fields.orderType = 'Buy Limit'
} else if (trades[i].fields.orderType === 3) {
trades[i].fields.orderType = 'Sell Limit'
} else if (trades[i].fields.orderType === 4) {
trades[i].fields.orderType = 'Buy Stop'
} else if (trades[i].fields.orderType === 5) {
trades[i].fields.orderType = 'Sell Stop'
} else if (trades[i].fields.orderType === 6) {
trades[i].fields.orderType = 'Bank Transaction'
}
// calculate R:R and TP + SL in pips and add result to object
if (stopLoss && takeProfit > 0) {
pipsRisked = Math.abs(trades[i].fields.orderOpenPrice - trades[i].fields.orderStopLoss);
pipsTargeted = Math.abs(trades[i].fields.orderOpenPrice - trades[i].fields.orderTakeProfit);
rrRatio = (pipsTargeted / pipsRisked);
trades[i].fields.pipsRiskedKey = pipsRisked;
trades[i].fields.pipsTargetedKey = pipsTargeted;
trades[i].fields.pipsRRKey = rrRatio;
}
}