创建对象属性,替换for循环中的每个对象属性

时间:2017-04-10 08:25:38

标签: javascript object for-loop

我正在尝试动态创建for循环内对象的属性,同时删除旧属性。

这是来源:

var input= { contents: 
   [ { source: 'source',
       sentiment: "positive",
       user_location_latitude: null,
       user_location_longitude: null
      }
      //...
   ]

这就是我想要的:

var input= { contents: 
       [ { source: 'source',
           sentiment: "positive",
           location: {long: null, lat: null}
           //with the contents of user_location_latitude and longitude
          }
          //...
       ]

这是我的代码:

for( var i=0 ;i< input.contents.length; i++){

              input.contents[i] = {"location": {"lat": input.contents[i].user_location_latitude,
               "lon":input.contents[i].user_location_longitude}}
              delete input.contents[i].user_location_latitude; 
              delete input.contents[i].user_location_longitude;


    }

我得到了:

{ contents: 
   [ { location: [Object] },
     { location: [Object] },
     { location: [Object] },
     { location: [Object] },
     { location: [Object] },
     { location: [Object] }
     //...
   ]
}

3 个答案:

答案 0 :(得分:2)

不应该只是;

input.contents[i]["location"] = {"lat": ...etc

您在位置后编制索引,但看起来想要在...之前执行...

答案 1 :(得分:2)

您的实际代码存在的问题是您忽略了其他对象属性,只是设置了location属性。

您还可以使用Array.prototype.map() method作为更好的方法来管理您的JSON数组,如下所示:

var input = {
  contents: [{
    source: 'source',
    sentiment: "positive",
    user_location_latitude: null,
    user_location_longitude: null
  }]
};

input.contents = input.contents.map(function(c) {
  return {
    source: c.source,
    sentiment: c.sentiment,
    location: {
      lat: c.user_location_latitude,
      long: c.user_location_longitude
    }
  };

});

console.log(input);

注意:

您可以通过这种方式看到您避免使用delete,只是以请求的格式格式化对象。

答案 2 :(得分:0)

试试这个input.contents[i].location。首先找到数组[i]然后应用对象键值location

&#13;
&#13;
var input= { contents: 
   [ { source: 'source',
       sentiment: "positive",
       user_location_latitude: null,
       user_location_longitude: null
      }
      
   ]}
for( var i=0 ;i< input.contents.length; i++){

       input.contents[i].location = {lang :input.contents[i].user_location_longitude , lat :input.contents[i].user_location_latitude }
delete input.contents[i].user_location_longitude;
delete input.contents[i].user_location_latitude;

    }
    console.log(input)
&#13;
&#13;
&#13;