简体   繁体   中英

How do I add a default value to JSON using JavaScript?

{
    "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!

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

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

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"
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM