0

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.

11
  • 4
    That is not valid JSON. The premise of your question is flawed, and I'm voting to close this as unclear. Commented Mar 16, 2015 at 17:22
  • 1
    Looking at your data, it desparately wants to be in an array...{cities:[{},{},...N]} Commented Mar 16, 2015 at 17:23
  • I think you want an array of objects: [ { "City" : c, "State" : s }, { }, { } ]... or an object with arrays: { "City" : [ c0, c1, c2 ], "State" : [ s0, s1, s2 ] }. Commented Mar 16, 2015 at 17:26
  • @zzzzBov If you tell me what the correct term is I will edit my post. Commented Mar 16, 2015 at 18:52
  • @Mr. Polywhirl Yes, you are correct. I made an error when generating the original post. I've amended it with your code which is how it should look. Thank you. Commented Mar 16, 2015 at 19:00

3 Answers 3

1

You should convert your data to an array of objects and simply operate on the array. The example below uses array.map to return an array with the State properties absent. However, there are numerous ways to skin this cat.

(edited to demonstrate a filtering preprocess before the map)

var data=[];

data.push({"City":"New York","State":"New York"});
data.push({"City":"Fargo","State":"North Dakota"});
data.push({"City":"Los Angeles","State":"California"});

var newData;

newData = data
  .filter(function(v){
    return v.State !=='California';
  })
  .map(function(v){
    return {City:v.City};
  });

Array.prototype.filter
Array.prototype.map

As others have indicated, you can't have duplicate properties in your JSON object. Your data is meant to be in an Array, not in one monster object.

Sign up to request clarification or add additional context in comments.

3 Comments

This looks promising and would be probably better since I have dozens of key/value pairs and only need a few so it would be better to pull out the ones I need instead of dump the ones that I don't. In the examples I looked up I've only seen it return one item each. Could that same method be used to return a few items?
yes, you can simply filter first and then map the filtered array. Updated the code to demonstrate.
Sorry, I wasn't clear. The use case I meant was taking an input array of city, state, zip, and country then outputting just city and state. The code I'm looking for using the map is: newData = data .map(function(v){ return {City:v.City, State:v.State}; }); Thanks for the help!
1

If you don't want to modify the original object, you can combine map and reduce to create filtered objects.

var data = [
    { "City" : "New York",    "State" : "New York"     },
    { "City" : "Fargo",       "State" : "North Dakota" },
    { "City" : "Los Angeles", "State" : "California"   }
];

var filterKeys = function(data, keysToFilter) {
  return data.map(function(item) {
    return Object.keys(item).reduce(function(result, key) {
      if (keysToFilter.indexOf(key) === -1) result[key] = item[key];
      return result;
    }, {});
  });
}

document.body.innerHTML = JSON.stringify(filterKeys(data, ['State']), null, '  ');
body {
  font-family: monospace;
  white-space: pre;
}

Result

[
  { "City": "New York" },
  { "City": "Fargo" },
  { "City": "Los Angeles" }
]

3 Comments

Yes, this is exactly the result that I want. It doesn't matter if I modify the original. So back to the original question, Is there a single operator which will remove all of the key/value pairs of a given key?
No, you need to iterate all objects.
OK, that's where I'm at already with my existing code so I'll probably just stick with that since I can feed in an arbitrary amount of key values that I want to work on. Thanks for your help.
0

you cant initiate an object with two identical keys.for example

var obj={city:"NEW YORK",city:"NEW JERSEY"}

city property will hold NEW JERSEY.because it's overwritten.

JSON.stringify(obj); // {"city":"NEW JERSEY"}

if you initiate an object with your json.your obj1 will hold only one city and state property.

   JSON.stringify(obj1); //{"City":"Fargo","State":"North Dakota"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.