Reputation: 25659
How do you update the properties of an object in javascript?
I would to update "id" of 68917 distance from 8.8 to 4.5...
I have access to lodash.js
[
{
"_id":68917,
"Distance":8.81,
"Lat":"42.65322175",
"Lon":"-73.77398886"
},
{
"_id":131277,
"Distance":"9.86",
"Lat":"42.654658",
"Lon":"-73.805866"
},
{
"_id":62450,
"Distance":6.58,
"Lat":"42.67457566",
"Lon":"-73.74902171"
}]
Upvotes: 0
Views: 153
Reputation: 1149
You could use the built-in "filter" function to get the item you want.
someObject.filter(function(item){return item._id === 68917;})[0].Distance = 4.5;
Here is an example:
Upvotes: 1
Reputation: 447
The code you have provided provides an array. If this is is representative of your code, you can then iterate over the objects in the array using a for loop:
If you assign the provided code to a variable named array, you can use this code to iterate over the items in the array.
Once you do that, you can then access the properties of the objects inside using the dot operator, locating and updating the correct item.
function echo (text){
document.getElementById("output").innerHTML += text + "<br/>"
}
var array = [
{
"_id":68917,
"Distance":8.81,
"Lat":"42.65322175",
"Lon":"-73.77398886"
},
{
"_id":131277,
"Distance":"9.86",
"Lat":"42.654658",
"Lon":"-73.805866"
},
{
"_id":62450,
"Distance":6.58,
"Lat":"42.67457566",
"Lon":"-73.74902171"
}];
echo("First item's distance " + array[0].Distance);
for(var i = 0; i < array.length; i++){
if(array[i]._id === 68917){
echo("Found item "+array[i]._id);
array[i].Distance = 4.45;
}
}
echo("First item's distance " + array[0].Distance);
I created a JS Fiddle that demonstrates this solution works; http://jsfiddle.net/gB5Nn/2/
Upvotes: 1
Reputation: 240
your_object[0].Distance = 4.5;
If you don't know the index beforehand:
_.findWhere(your_object, {'_id': 68917}).Distance = 4.5;
Upvotes: 5