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!

1

3 Answers 3

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

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

Comments

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

2 Comments

result will be an array of 5 instances of the object, not the resulting object itself.
I updated the answer with forEach instead of map to change on the original variable
-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"
   }
}

Comments