Javascript: addJsonNodes - Adds one or more elements to an existing JSON object. If the element exists it will overwrite the value. If the element is a new object, or two, they will be created
/*
*
digitalData is used as an example of a JSON analytics object that we want to insert data into via addJsonNodes()
*
*/
digitalData = {
pageInstanceID: "Boe:MyBoeingFleet:Toolbox:Home-staging",
page: {
pageInfo: {
pageName: "Boe:MyBoeingFleet:Toolbox:Home",
destinationURL: document.location,
language: "en-us",
geoRegion: "us"
},
category: {
primaryCategory: "toolbox",
subCategory1: "asdf",
subCategory2: "",
subCategory3: "",
pageType: "universal"
},
user: {
userID: "12345",
userAccessLevel: "level 1",
userAirlineCode: "dl",
userPersona: "manager"
}
}
};
/*
*
newData is used as an example of a JSON analytics object that we want to insert into digitalData via addJsonNodes()
*
*/
var newData=[
{"name":"id", "value":"2"},
{"name":"digitalData.page.category.subCategory1", "value":"first tool"},
{"name":"digitalData.page.pageInfo.zip","value":"97217"}
]
/**
* Adds one or more elements to an existing JSON object. If the element exists it will overwrite the value. If the element is a new object, or two, they will be created
* The format of the JSON elements to be added:
var newData=[
{"name":"digitalData.id", "value":"2"},
{"name":"digitalData.page.category.subCategory1", "value":"first tool"}
]
It is a collection of "element" nodes. Each node has two attributes: name and value.
name: [is the location of the element in the JSON it should be added. Include the object name. ex: digitalData
value: [is the value to be written]
* @param {object} dataObj [the JSON object where the data should be inserted]
* @param {array} elements [the data that should be inserted into dataObj, for example, see newData above]
* @return {nothing}
*/
function addJsonNodes(dataObj, elements) {
// Loop through the elements to be added
for (var e in elements) {
//Grab the name/location of the element to be added.
aNodePath = elements[e].name.split(".").slice(1,elements[e].length);
var obj = dataObj||{};
// Dig down into dataObj to see if we need to create a new object or assign the value
for (var i in aNodePath) {
// Not the end of the object.
if(i!=aNodePath.length-1){
//Is there a value? If not dig deeper
if (obj === null || typeof obj[aNodePath[i]] === 'undefined'){
//console.info("created: ", aNodePath[i], " object: ", obj[aNodePath[i]] );
obj[aNodePath[i]] = {};
}
// Set the object equal to the next level in aNodePath
obj = obj[aNodePath[i]];
}
// The end of the object
else{
// Set the value to the value in the elements param
obj[aNodePath[i]] = elements[e].value;
//Reset object back to the original object
obj = dataObj;
}
}
}
}
//Usage
addJsonNodes(digitalData,newData);