I have an dot notated array such as:
var base = ['a.b.c','a.e','h'];
I also have a reference object:
var reference = {
a: {
b: {
c:"Hello",
d:"you"
},
e:"beautiful",
f:"and"
},
g:"kind",
h:"World"
};
I need to build an object out of the base notated string and get the values from the reference object. Unfortunately, I cannot change the base nor the reference.
I have it working for each individual part of the array but the problem is when I try to merge the object. It overwrites the value a.b.c with a.e.
My desired output would be:
var desiredOutput = {
a: {
b: {
c:"Hello"
},
e:"beautiful"
},
h:"World"
};
However, with the code below my output is:
var output = {
a: {
e: "beautiful"
},
h: "World"
};
Any help would be appreciated. I am limited to < ES5 but could use some polyfills such as Object.assign if needed.
function convert(base,reference) {
var obj = {};
var getObjectValue = function(string, reference) {
var i = 0;
while (reference && i < string.length) {
reference = reference[string[i++]];
}
return reference;
};
for (var n = 0; n < base.length; n++) {
var s = base[n].split("."),
x = obj;
for(var i = 0; i < s.length-1; i++) {
x = x[s[i]] = {};
}
x[s[i]] = getObjectValue(s,reference);
}
return obj;
}
var base = ['a.b.c','a.e','h'];
var reference = {
a: {
b: {
c:"Hello",
d:"you"
},
e:"beautiful",
f:"and"
},
g:"kind",
h:"World"
};
var desiredOutput = {
a: {
b: {
c:"Hello"
},
e:"beautiful"
},
h:"World"
};
console.log(convert(base,reference));