Javascript 向我的对象数组添加新字段

Javascript 向我的对象数组添加新字段,javascript,arrays,json,Javascript,Arrays,Json,我得到了一个很好的对象数组: [ { "_id": "5908906b53075425aea0b16d", "property": "ATL-D406", "discount": 10, "hot": true }, { "_id": "5908906b53075425aea0b16f", "prop

我得到了一个很好的对象数组:

   [
        {
            "_id": "5908906b53075425aea0b16d",
            "property": "ATL-D406",
            "discount": 10,
            "hot": true
        },
        {
            "_id": "5908906b53075425aea0b16f",
            "property": "WAT-806",
            "discount": 20,
            "hot": true
        },
        {
            "_id": "5908906b53075425aea0b171",
            "property": "ANA-C202",
            "discount": 30,
            "hot": true
        }
    ]
我试试这个

hotdealArray[i].priceNight = result.res.priceNight;
其中给出错误:无法设置未定义的属性“priceNight”

如何向hotdealArray添加新字段

以下是我的for循环(按要求):

    for (var i=0; i<hotdealArray.length; i++) {
        var priceNight = 0;
        priceController.getPrice (
            { "body": { "propertyID": hotdealArray[i].property } }, 
            function(result) {
                if (result.error == true) {
                    throw new Error(result.err);
                } 
                priceNight = result.res.priceNight;
                console.log ("priceNight inside: " + priceNight);
            }
        );
        console.log ("priceNight outside: " + priceNight);
        hotdealArray[i].priceNight = priceNight;
    };

还有其他方法,但避免作用域问题的一种方法是将内部回调封装在IIFE中,该IIFE在该作用域中显式定义了i

        function(result) {
            if (result.error == true) {
                throw new Error(result.err);
            } 
            console.log ("priceNight: " + result.res.priceNight);
            hotdealArray[i].priceNight = result.res.priceNight;
        }
变成

(function (i) {
  return function(result) {
    if (result.error == true) {
      throw new Error(result.err);
    } 
    console.log ("priceNight: " + result.res.priceNight);
    hotdealArray[i].priceNight = result.res.priceNight;
  };
})(i);

您需要提供更多的上下文。hotdealArray不是您在引用时发布的数组,或者我不是0、1或2。如果没有更多的代码,我们就无法调试。@ArnavAggarwal如果您使用console.loghotdealArray[i].property,那么您将得到一个值。它已经有了值,我只需要在每个记录中添加一个新的priceNightfield。请添加您用来循环arrayAs的代码,其中包含大多数此类问题,如果您能提供一个示例,让我们可以看到正在运行的代码,并演示该问题,这是最好的。正如@Lixus所演示的,使用您提供的代码的MCVE并没有演示问题。哦,这是一个范围错误。这改变了一切。这可能会奏效。我只是不明白为什么我不能从result函数内部访问任何scopes变量。很奇怪。让我更新这个问题,让你看看。为什么我不能访问函数result{}中的任何内容?为什么我在priceController之后不能做任何事情。getPrice它完全忽略了这些行。因为它是一个回调函数,它对任何本地定义的变量都没有作用域,回调往往具有全局作用域。要么有全局范围的变量,要么将它们设置为IIFE中的参数,类似于我对I所做的。我想我找到了它-它实际上做的一切都是正确的,唯一的问题是getPrice并不是作为承诺设置的,所以一旦整个循环完成,这就是priceNight开始返回的时候,那时我们不再在代码/循环中。我需要将调用隔离到一个函数中,并做出承诺。
(function (i) {
  return function(result) {
    if (result.error == true) {
      throw new Error(result.err);
    } 
    console.log ("priceNight: " + result.res.priceNight);
    hotdealArray[i].priceNight = result.res.priceNight;
  };
})(i);