I am working with JSON data in a JavaScript object like this:
var data = [
{ "City" : "New York", "State" : "New York" },
{ "City" : "Fargo", "State" : "North Dakota" },
{ "City" : "Los Angeles", "State" : "California" }
];
And I want to remove state data so it ends up like this:
var data = [
{ "City" : "New York"},
{ "City" : "Fargo"},
{ "City" : "Los Angeles"}
];
Currently I'm looping through and removing it but is there a way to remove the city from the object without having to loop through?
I found the "delete" operator ("The delete operator removes a property from an object.") but it seems to only work if there is just one item with that property, not globally as in the example object.
delete object["State"] //doesn't work
Edit: My bad. I copy/pasted and edited incorrectly. I have changed the original post to use correct format as supplied in Mr. Polywhirl's answer.
Edit: I ended up using the map method as suggested by mccainz. Using map allows for pulling all of a certain key/value pair (like city) from one array into another. You can also pull multiple like
newData = data
.map(function(v){
return {City:v.City, State:v.State};
});
It will work for my purposes and is better since I'm keeping the minority of the key/value pairs. However, it doesn't appear that there are any solutions for performing the task in the original question. For example, if you had 100 different key/value pairs per array item, you'd have to add 99 to a new array instead of being able to just remove one from the existing.
[ { "City" : c, "State" : s }, { }, { } ]... or an object with arrays:{ "City" : [ c0, c1, c2 ], "State" : [ s0, s1, s2 ] }.