2017-04-10 106 views
2

我试图动态创建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] } 
    //... 
    ] 
} 

回答

2

它不应该只是;

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

您的位置后,索引,但看起来像你想之前做...

0

试试这个input.contents[i].location。首先找到阵列[i]然后申请对象键值location

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)

2

你的实际代码的问题是,你是ign或者其他对象属性,并设置location属性。

您还可以使用Array.prototype.map() method作为一个更好的方法来ierate您的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,并且只是以请求的格式格式化对象。