This article will help us to create dynamic JSON object using JavaScript. This code will useful for generating nested JSON object dynamically. Benefits of dynamic nesting objects and arrays using JavaScript find the question and answer
1) How to dynamically create JSON nested objects using JavaScript / Front End? This tutorial will help us to create the JSON object using JavaScript. 2) Is there any limit of generating the nested JSON object/array dynamically? Whatever the array passed to the function will generate the JSON object. No limit. 3) Will the function has flexible to give own key to the JSON nested values / Object? Yes. It has that option to assign our own / dynamic key to the dynamically generated JSON nested Object / array.
Javascript
Create function for to return the JSON object
Below “getObjectFormat()” function will return the object (Take care by createChildRows() function). the params to be passed are title, childrows and key
“createChildRows()” function will return the Nested JSON Object Javascript. the params to be passed are array, childrows and key
- title param: Title of that node
- childrows param: Will be nested the previous objects(For initial start function need the childrows json object param to be passed)
- key param: Will be set as custom key to the node(Empty will set as “childRows” as a key)
function getObjectFormat(title,childRows,key){
var setKey = (key == null)?("childRows"):(key);
return {
title: title,
[setKey]: childRows
};
};
function createChildRows(array,childRows,key = null){
var array = array.reverse();
array = array.filter(function(n){return (n != undefined && n != "") });
// Initial child rows
var formate = getObjectFormat(array[0],childRows,key);
for(var i = 1; i < (array.length); i++){
formate = getObjectFormat(array[i],formate,key);
};
return formate;
};
// Demo call. Console the result of generated dynamic Json Objects
var array = ("test1|test2|test3|test4").split("|");
console.log(createChildRows(array,{"title":"Last Child Row"},"more"));
Leave a Reply