1
{
    "Les Miserables":{
        "lang": "French",
        "type": "Movie"
    },
    "Some German Book":{
        "lang": "German",
        "type": "Book"
    },
    "Gangnam Style":{
        "lang": "Korean",
        "type": "Song"
    },
    "Captain America":{
         "type": "Comic Book"
    },
    "Some song":{
         "type": "Song"
    }
}

I want all the objects that don't have a language to be set to English by default.

How do I do this through JavaScript? I want to update the original JSON object, not create a new one.

Example Output:

{
    "Les Miserables":{
        "lang": "French",
        "type": "Movie"
    },
    "Some German Book":{
        "lang": "German",
        "type": "Book"
    },
    "Gangnam Style":{
        "lang": "Korean",
        "type": "Song"
    },
    "Captain America":{
         "type": "Comic Book",
         "lang": "English"
    },
    "Some song":{
         "type": "Song",
         "lang": "English"
    }
}

Thanks in advance!

3 Answers3

2

You can just iterate over the object keys with Object.keys, and set the property you want to its default value if it does not exist:

var obj = {
  "Les Miserables": {
    "lang": "French",
    "type": "Movie"
  },
  "Some German Book": {
    "lang": "German",
    "type": "Book"
  },
  "Gangnam Style": {
    "lang": "Korean",
    "type": "Song"
  },
  "Captain America": {
    "type": "Comic Book"
  },
  "Some song": {
    "type": "Song"
  }
};

// for each key of the object...
for (let key of Object.keys(obj)) {
  // set the "lang" property to "English" if it does not exist
  if (obj[key].lang == null) {
    obj[key].lang = "English";
  }

  // set more default values the same way if you want
}

console.log(obj);
George
  • 6,630
  • 2
  • 29
  • 36
Frxstrem
  • 38,761
  • 9
  • 79
  • 119
1

You can use Object.keys combine with Array#forEach to do it

var obj = {
        "Les Miserables":{
            "lang": "French",
            "type": "Movie"
        },
        "Some German Book":{
            "lang": "German",
            "type": "Book"
        },
        "Gangnam Style":{
            "lang": "Korean",
            "type": "Song"
        },
        "Captain America":{
             "type": "Comic Book"
        },
        "Some song":{
             "type": "Song"
        }
    };

    Object.keys(obj).forEach( key => {
      if (!obj[key].lang) {
        obj[key].lang = 'English';
      }
    });
    
    console.log(obj);
taile
  • 2,738
  • 17
  • 29
-1

You can use a for loop to achieve this .

code

//Assume data is your json
for(var key in data){
   if(!data[key].lang)
   {
     data[key][lang]="english"
   }
}