简体   繁体   English

如何在循环内动态地向现有的 Javascript 对象添加新的键:值对

[英]How can I add a new key:value pair to an existing Javascript object dynamically within a loop

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?我使用此线程尝试了两种不同的方法: 如何将键/值对添加到 JavaScript 对象? :

Using assign :使用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 :使用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;
    }
}

As you mentioned trades is an array.正如你提到的, trades是一个数组。 When you do Object.keys() on an array, you get the indexes of that array.当您对数组执行Object.keys()时,您将获得该数组的索引。 This can be simplified to just trades.length as they are the same thing.这可以简化为只是trades.length因为它们是相同的。

Currently, you're looping over trades , which allow you to access each object in your array.目前,您正在遍历trades ,这允许您访问数组中的每个对象。 Each object has a trades property with an array, which you also need to loop over.每个对象都有一个带有数组的trades属性,您还需要循环遍历该数组。 This means you need a nested loop.这意味着您需要一个嵌套循环。 One to loop over all your objects in your larger, and another to loop over all your objects in your trades property array.一个循环遍历较大的所有对象,另一个循环遍历您的trades属性数组中的所有对象。 This can be done like so:这可以像这样完成:

 const tradesTotal = [{ "trades": [{ "fields": { "orderOpenPrice": "1.40000", "orderTakeProfit": "1.50000", }, }, { "fields": { "orderOpenPrice": "1.30000", "orderTargetPrice": "1.50000", } }, { "fields": { "orderOpenPrice": "1.50000", "orderTargetPrice": "1.55000", } }, ] }]; for (var i = 0; i < tradesTotal.length; i++) { var trades = tradesTotal[i].trades; for (var j = 0; j < trades.length; j++) { var pipsTargeted = Math.abs(trades[j].fields.orderOpenPrice - trades[j].fields.orderTakeProfit); trades[j].fields.pipsTargetedKey = pipsTargeted } } console.log(tradesTotal);

Just use Array.prototype.map function and spead operator :只需使用Array.prototype.map函数和扩展运算符

const trades = [
  {
    "fields": {
      "orderOpenPrice": "1.40000",
      "orderTakeProfit": "1.50000",
    },
  },
  {
    "fields": {
      "orderOpenPrice": "1.30000",
      "orderTakeProfit": "1.50000",
    }
  },
  {
    "fields": {
      "orderOpenPrice": "1.50000",
      "orderTakeProfit": "1.55000",
    }
  }
]

const mappedTrades = trades.map(trade => {
  const {orderOpenPrice, orderTakeProfit} = trade.fields
  return {
     ...trade,
     fields: {
        ...trade.fields,
        pipsTargetedKey: Math.abs(Number(orderOpenPrice) - Number(orderTakeProfit))
     }
  }
})

Another way is to use something like Proxy or Object.observe .另一种方法是使用诸如ProxyObject.observe 之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM