3

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"
    }
    ],
1
  • In this case if you are just using strings for keys would you not be best just using a object selectedLanguageDetails={} and then you could just JSON.stringify it. Would save a lot of leg work. Your can also set object keys with dynamic data using '[a]: 'test''. I have never found a need to use Map over {}. Its not like java where you have to new up Maps etc. Commented Oct 27, 2017 at 8:52

2 Answers 2

5

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

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

Comments

2

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

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.