I am currently developing an app with Angular 4. I want to know if it is possible to convert a map to json in angular ? this is my map stucture
selectedLanguageDetails.set("languageName", element.languageName);
selectedLanguageDetails.set("languageCode", element.languageCode);
selectedLanguageDetails.set("internalId", element.internalId);
json structure
"languages": [
{
"internalId": 101,
"languageCode": "ms",
"languageName": "Malay"
}
],
To convert to an object - spread the Map to get an array of [key, value] pairs, and Array#reduce to an object.
To convert to a string - Instead of reduce, use Array#map to convert each pair to a string, and Array#join the result:
const selectedLanguageDetails = new Map(); selectedLanguageDetails.set("languageName", "English"); selectedLanguageDetails.set("languageCode", "en"); selectedLanguageDetails.set("internalId", 15); const obj = [...selectedLanguageDetails].reduce((o, [key, value]) => (o[key] = value, o), {}); const string = [...selectedLanguageDetails].map(([key, value]) => `${key}:${value}`).join(', '); console.log(obj); console.log(string);
For converting Map to JSON object or string you can use below code.
let jsonObject = {};
selectedLanguageDetails.forEach((value, key) => {
jsonObject[key] = value
});
string jsonString = JSON.stringify(jsonObject);
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.