3

I have a javascript MAP object which is holding key as a string and value as a javascript array, each array is holding set of strings inside it. I want to convert the map of arrays into a json object in javascript.

Here is the code which i tried

function addRole() {

 var jsonObjectOfMap={};
    subMenuSelectedIdMap.forEach(function(items,key,subMenuSelectedIdMap){
        jsonObjectOfMap[key]=JSON.stringify(items);
    }); 
    alert(JSON.stringify(jsonObjectOfMap));

I am getting the json object as like this {"1004":"[1005,1006,1023]","1007":"[1008,1053]"}

But is this json format object is valid and what i have to do if i want it the format as this: {"1004":["1005","1006","1023"]","1007":["1008","1053"]}

Please help me out

3
  • jsonObjectOfMap[key]=items;JSON.stringify() doesn't need to be called on each individual object. It's usually only necessary to call it once on the root object – JSON.stringify(jsonObjectOfMap). It already behaves recursively and will stringify any (compatible) values contained within. Commented Dec 8, 2016 at 5:06
  • I tried that way but its giving me like this : {"1004":[1005,1006,1023],"1007":[1008,1053]} Commented Dec 8, 2016 at 5:30
  • Can you show us the JSON file? Commented Dec 8, 2016 at 5:38

1 Answer 1

0

If the inner-most values are all numbers and you want them as strings in the end result, you'll have to convert each number individually to a string.

You can do that with another loop over each items using .map() and either calling String() or .toString() for each number:

subMenuSelectedIdMap.forEach(function (items, key, subMenuSelectedIdMap){
    jsonObjectOfMap[key] = items.map(function (item) {
        return String(item); // or `return item.toString();`
    });
});

Optionally, since String() only acknowledges one argument (with the other two that .map() passes being ignored), the loop over items could be shortened to:

jsonObjectOfMap[key] = items.map(String);
Sign up to request clarification or add additional context in comments.

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.