I would like to convert the below input fields into nested json file structure as per below in my html page, I've tried in a couple of ways, but unable to get. Here I am getting these inputs through angularjs ng-repeat. Please help me that how can i implement. Thanks in advance.
<form id="text" method="post" action="" enctype="multipart/form-data">
<input type="hidden" value="/images/Image1.nii" name="imageurl">
<input type="hidden" value="3d0" name="3d" >
<input type="hidden" value="sliceX0" name="sliceX">
<input type="hidden" value="sliceY0" name="sliceY">
<input type="hidden" value="sliceZ0" name="sliceZ">
<input type="hidden" value="/images/Image2.nii" name="imageurl">
<input type="hidden" value="3d1" name="3d1" >
<input type="hidden" value="sliceX1" name="sliceX">
<input type="hidden" value="sliceY1" name="sliceY">
<input type="hidden" value="sliceZ1" name="sliceZ">
</form>
As I am getting it in a normal json structure:
[{"name":"imageurl","value":"/images/Image1.nii"},{"name":"3d","value":"3d0"},{"name":"sliceX","value":"sliceX0"},{"name":"sliceY","value":"sliceY0"},{"name":"sliceZ","value":"sliceZ0"},{"name":"imageurl","value":"/images/Image2.nii"},{"name":"3d","value":"3d1"},{"name":"sliceX","value":"sliceX1"},{"name":"sliceY","value":"sliceY1"},{"name":"sliceZ","value":"sliceZ1"}]
but I need like below:
[
{"name":"imageurl","value":"/images/Image1.nii", parts: [
{"name":"3d","value":"3d0"},
{"name":"sliceX","value":"sliceX0"},
{"name":"sliceY","value":"sliceY0"},
{"name":"sliceZ","value":"sliceZ0"},
]},
{"name":"imageurl","value":"/images/Image2.nii", parts: [
{"name":"3d","value":"3d1"},
{"name":"sliceX","value":"sliceX1"},
{"name":"sliceY","value":"sliceY1"},
{"name":"sliceZ","value":"sliceZ1"}
]}
]
How to convert form input fields to nested json structure using jquery
You should use a helper library like lodash to do such data manipulation.
Here is a conversion which I did with lodash:
// split the data into chunks of 5 elements each
var chunks = _.chunk(data, 5);
// for every chunk create the desired object with the parts
var desired = _.map(chunks, function(c) {
var image = c[0];
image.parts = _.rest(c);
return image;
});
console.log(desired);
Here is a working Plunker
You should wrap each image group in its own container. But if you must keep your current structure:
var el = document.querySelectorAll('#text [type="hidden"]');
var arr = [];
var obj = {};
var push = false;
for(var i = 0; i < el.length; i ++){
if(el[i].value.indexOf('images') > -1){
if(push){
arr.push(obj);
obj = {};
};
obj.name = 'imageurl';
obj.value = el[i].value;
push = true;
}
obj.parts = obj.parts || [];
obj.parts.push({
name: el[i].name,
value: el[i].value
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.