Is it possible to dynamically generate an object with an array of strings in dot notation? The idea is to construct a JSON object from a CSV file, filter the properties, and create a new JSON object.
Let's say we want to pass something like this...
var obj = {};
var keyArray = ['meta', 'logos', 'warranty', 'specs', 'specs.engine', 'specs.engine.hp', 'specs.engine.rpm', 'specs.engine.manufacturer'];
The desired outcome would be...
obj = {
meta: {
},
logos: {
},
specs: {
engine: {
hp: {
}
}
}
}
Here is the key function
function addObjectsByKey(obj, keyArray) {
for (var key in keyArray) {
// Check if keyword is not in object notation
if (!(keyArray[key].match(/\./))) {
// If the object property is not set, set it
if (!(obj[keyArray[key]])) {
obj[keyArray[key]] = {};
}
} else {
// Split array element (in dot notation) into an array of strings
// These strings will be object properties
var pathAsArray = keyArray[key].split('.');
var path = null;
for (var k in pathAsArray) {
if (path == null) {
obj[pathAsArray[k]] = {};
path = pathAsArray[k];
} else {
obj[path][pathAsArray[k]] = {};
path += '.' + pathAsArray[k];
}
}
// throw Error('end');
}
}
// return obj;
}