I have a Map<String, List<Object>>
and i want to convert it to JSON
.
Here is what I have:
Point 1: Declaring variables
var map = new Map(), //map
jsonObject= {}, // oject that needs to be converted to JSON
value1 = { topic: "someText1", status: "0", action: "1", comment: "someComment1" }, // values of Map
value2 = { topic: "someText2", status: "0", action: "0", comment: "someComment2" },
value3 = { topic: "someText3", status: "1", action: "1", comment: "someComment3" };
Point 2: function to populate multi-value map
function populateMap(map, k, v) {
map[k] = map[k] || [];
map[k].push(v);
}
Point 3: populating Map
// key of map is concatenation of various attributes from web page, separated by |
populateMap(map, 'release|attachment|license1', value1);
populateMap(map, 'release|attachment|license1', value2);
populateMap(map, 'release1|attachment1|license1', value1);
populateMap(map, 'release1|attachment1|license2', value2);
populateMap(map, 'release1|attachment1|license3', value3);
populateMap(map, 'release2|attachment2|license2', value1);
populateMap(map, 'release2|attachment2|license2', value2);
Point 4: iterating map and populating jsonObject
for (var i in map) {
var keys = i.split('|'), // splitting keys based on |
last = keys.pop(),
values = map[i];
values.forEach(function (item, index) {
keys.reduce((r, a) => r[a] = r[a] || {}, jsonObject)[last] = item;
});
}
Point 5: current output (jsonObject printed on console)
{
"release": {
"attachment": {
"license1": "[Object]"
}
},
"release1": {
"attachment1": {
"license1": "[Object]",
"license2": "[Object]",
"license3": "[Object]"
}
},
"release2": {
"attachment2": {
"license2": "[Object]"
}
}
}
Point 6: expected output (jsonObject)
{
"release": {
"attachment": {
"license1": "[Object, Object]" // expecting array of objects here ^^
}
},
"release1": {
"attachment1": {
"license1": "[Object]",
"license2": "[Object]",
"license3": "[Object]"
}
},
"release2": {
"attachment2": {
"license2": "[Object, Object]"
}
}
}
^^ Since map is having array of objects for that key, So i want to have array of objects in jsonObject
.
Can someone help me with tweak needs to be done in map
traversal in Point 4 to obtain expected result?
You use methods like
.set
,.get
,.has
, and.delete
to interact withMap
; setting its elements as properties is incorrect.Then iterating over the map looks like this:
and your
setPath
implementation stays pretty much the same:In toto: