Defoe
Defoe

Reputation: 371

create object property replacing every object property inside for loop

I'm trying to create dynamically a property of an object inside a for loop while I delete the old properties.

This is the source:

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

This is what I want:

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

This is my code:

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;


    }

And I'm getting:

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

Upvotes: 2

Views: 27

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

The problem with your actual code is that you are ignoring other object properties, and just setting the location property.

You can also use Array.prototype.map() method as a better approach to ierate your JSON array, like this:

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);

Note:

You can see that this way you are avoiding using delete and just formatting your object in the requested format.

Upvotes: 2

prasanth
prasanth

Reputation: 22500

try this input.contents[i].location .first find the array [i] then apply object key value 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)

Upvotes: 0

Milney
Milney

Reputation: 6417

Should it not just be;

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

You are indexing after location but looks like you want to do it before...

Upvotes: 2

Related Questions