Need some advice on how to create a JSON object by looping through an array without duplicating some of the keys
I am given an array that I need to split up into an object but without duplicating one of the keys
For example:
var myArray = [
"name/ServiceV1/20190201/1/index.html",
"name/ServiceV2/20190201/1/index.html",
"name/ServiceV2/20190201/2/index.html",
"name/ServiceV2/20190201/3/index.html",
"name/ServiceV2/20190203/3/index.html",
"name/ServiceV3/20190213/1/index.html"
];
Returns
[
{
"name": {
"ServiceV1": {
"20190201": {
"1": "index.html"
}
},
"ServiceV2": {
"20190201": {
"1": "index.html",
"2": "index.html",
"3": "index.html"
},
"20190203": {
"1": "index.html"
},
},
"ServiceV3": {
"20190213": {
"1": "index.html"
},
}
}
}
]
How could I get this to work? The code below is what I have already
var jsonify = function() {
var myArray = [
"name/ServiceV1/20190201/1/index.html",
"name/ServiceV2/20190201/1/index.html",
"name/ServiceV2/20190201/2/index.html",
"name/ServiceV2/20190201/3/index.html",
"name/ServiceV2/20190203/3/index.html",
"name/ServiceV3/20190213/1/index.html"
];
let end = [];
// Loop through all the myArray items
for (let i = 0; i < myArray.length; i++) {
var itemparts = myArray[i].split("/");
var newObject = {};
var value = itemparts.pop();
while (itemparts.length) {
var obj = {};
if (newObject.hasOwnProperty(itemparts.pop())) {
return;
} else {
newObject[itemparts.pop()] = value;
}
obj[itemparts.pop()] = value;
value = obj;
}
end.push(value);
}
// return the results
return end;
};
But that returns this:
[
{
"name": {
"ServiceV1": {
"20190201": {
"1": "index.html"
}
}
}
},
{
"name": {
"ServiceV2": {
"20190201": {
"8": "index.html"
}
}
}
},
{
"name": {
"ServiceV2": {
"20190201": {
"9": "index.html"
}
}
}
},
{
"name": {
"ServiceV2": {
"20190201": {
"17": "index.html"
}
}
}
}
]
So I'm kinda lost on where to go next