Create JSON from dynamic HTML form - javascript

Here is my fiddle: DEMO
I want my JSON to be as below on click of "Save Actions" and when the category is "SMS". I'm not able to achieve this.
Also, the form fields change on change of category.
{
"name": "",
"category": "SMS",
"description": "",
"apiUrl": "",
"apiMethod": "GET",
"apiPayload": {
"senderName": "",
"number": "",
"message": ""
},
"#class": "action"
}
Any help would be much appreciated. Thanks :)

Move the apiPayload out of the reduce callback function.
And assign the value after the reduce loop.
$('#saveActions').on('click', function(e) {
var apiPayload = {};
var jsonData = $('form.form-horizontal#events')
.find(':input:not(button):not(#new-option-event)').get()
.reduce(function(acc, ele) {
if (ele.closest('.payload')) {
var i = 0;
apiPayload[ele.name] = ele.value.trim();
} else {
acc[ele.name] = ele.value.trim();
}
return acc;
}, {});
jsonData['apiPayload'] = apiPayload;//assign value
jsonData['#class'] = "action";
alert(JSON.stringify(jsonData, null, 4));
});

Related

How to process multidimensional array from jQuery Sortable (nested list)?

I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):
{
"codes": [
[
{
"id": "code_run",
"code": "run",
"name": "code_when_run"
},
{
"id": "",
"code": "loop",
"name": "code_block_repeat",
"children": [
[
{
"id": "",
"code": "up",
"name": "code_arrow_up"
},
{
"id": "",
"code": "up",
"name": "code_arrow_up"
}
]
]
}
]
]
}
Here's my code from the jQuery sortable's example :
let oldContainer, codeBlockId, codeBlockItem;
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
var data = group.sortable("serialize").get();
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString);
_super($item, container);
},
});
How can I process the sub array (children[]) ?
I have plan to make it all block as a real codes, so it could execute with another function.
I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :
for (var i = 0; i < 3; i++) {
moveUp();
}
Any help or suggest would be great, thanks!
If your JSON string will always look like this. Then you can target there “children" array like this.
I wrote this code base only on the format of the JSON that you have above.
const childrenArr = jsonString.codes[0][1].children;
Based on the code we’re you are stringifying your data this code should work.
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString),
ChildrenArr = jsonString.codes[0][1].children;
I've found a solution for my problem, here's the code :
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
if($item.hasClass('RepeatCode')){
$item.attr('id','block_loop_function_drag');
}
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
$(".coding-script").empty();
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
$hasID = document.getElementById('block_loop_function_drag');
var data = group.sortable("serialize").get();
// console.log(data);
for(var i = 0; i < data[0].length; i++){
if($hasID){
$item.attr('id','block_loop_function_'+i+'');
}
var obj = data[0][i];
if(obj.hasOwnProperty("children")){
var objChildren = obj.children[0];
console.log(obj.code +'-'+i);
ConvertToCodeScripts(obj.code, i);
for(var j = 0; j < objChildren.length; j++){
console.log('loop-'+i+'-'+objChildren[j].code);
ConvertToCodeScripts('loop-'+i+'-'+objChildren[j].code, i);
}
}
else{
console.log(obj.code);
ConvertToCodeScripts(obj.code, i);
}
console.log('lha - '+i);
}
_super($item, container);
},
});
But let me know if you guys have a better solution.
Cheers

How to loop through the response text of JSON file?

I have a JSON file that contains object like that:
{
"status": "ok",
"feed": {
},
"items": [
{
"title": "",
"author": ""
},
{
"title": "",
"author": ""
},
{
"title": "",
"author": ""
}
]
}
I want to loop through the items and get each item data like title and author.
The code I tried:
var json = $.getJSON({'url':"filejson" , 'async': false});
json = JSON.parse(json.responseText);
$.each(json, function(index , item) {
console.log(json[index]);
});
It would appear the sync version of it acts in a weird way,
var json = JSON.parse($.getJSON({'url':"filejson" , 'async': false}).responseText);
let items = json.items;
items.forEach(item=>{
console.log(item.title, item.author);
})
As a sidenote, you should really not be using async: false.
Object.keys(json).forEach(function(key) {
console.log(json[key])
})
// or if supported/polyfilled
Object.values(json).forEach(function(value) {
console.log(value)
})
Use map():
data.map(d => ({title: d.title, author: d.author}));
Please use the following code
var json = $.getJSON({'url':"filejson" , 'async': false});
json = JSON.parse(json.responseText);
$.each(json.items, function(key , value) {
console.log(value['title'] + " : "+ value['author']);
});

Lodash compare/merge object to array

I need to compare/merge 2 objects with diferent structure using Lodash.
data= [
{
"name": "EMPRESA",
"value": ""
},
{
"name": "DESIGEMPRESA",
"value": "CMIP"
},
{
"name": "UTILIZADOR",
"value": ""
},
{
"name": "CD_INDICADOR",
"value": ""
},
{
"name": "DT_INI_INDICADOR",
"value": ""
},
{
"name": "DT_INI",
"value": "2017-12-13"
},
.....
]
and
dbcolsData={
"EMPRESA": "",
"UTILIZADOR": "paulo.figueiredo",
"CD_INDICADOR": "",
"DT_INI_INDICADOR": "",
"DT_INI": "",
"DT_FIM": ""
}
The question is how i can fill the values of data with the values of dbcolsData ?
Lets say put the values of dbColsData in data
Thanks in advance
Try something like this:
_.forEach(data, function(object){
object.value = dbcolsData[object.name];
})
Use Array#map (or lodash's _.map()) to iterate the data, and get the results from dbcolsData:
var data = [{"name":"EMPRESA","value":""},{"name":"DESIGEMPRESA","value":"CMIP"},{"name":"UTILIZADOR","value":""},{"name":"CD_INDICADOR","value":""},{"name":"DT_INI_INDICADOR","value":""},{"name":"DT_INI","value":"2017-12-13"}];
var dbcolsData = {"EMPRESA":"","UTILIZADOR":"paulo.figueiredo","CD_INDICADOR":"","DT_INI_INDICADOR":"","DT_INI":"","DT_FIM":""};
var result = data.map(function(o) {
return Object.assign({ data: dbcolsData[o.name] }, o);
});
console.log(result);
Reduce data to the dbcolsData structure :
var myData = data.reduce((o, nvO) => Object.defineProperty(o, nvO.name, {value: nvO.value}), {})
->
Now you can use lodash comparison functions like _.isEqual :
_.isEqual(myData, dbcolsData)

angularjs: Push is not a function

I have a JSON object like this:
var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};
And post is passed to the function given below from the front end.
var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here
myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};
But doing so, I get a JavaScript error saying push is not a function in line likedPost.likers.push(userObject);
And userObject is returned by vm.userInfo() and it looks like this:
vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};
and the returned JSON is like this:
{"id":"12","firstName":"Amelia","lastName":"Earheart"}
Can anyone help me figure out the cause of this issue?
UPDATE:
{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}
This is what I get upon console.log(likedPost);
The output clearly specifies that likers is not defined. You can put a validation check before using push() method.
//if likedPost.likers is not defined, it will define it as an array
likedPost.likers = likedPost.likers || [];
//Do the push operation
likedPost.likers.push(userObject);
Your likedPost object doesn't have the likers array you expect. Probably you can see if that exists before trying to push.
if (typeof likedPost !== 'undefined')
likedPost.likers.push(userObject);

Sorting out JSON data into a smaller file using nodejs

I have a large JSON file, I am trying to pull out specific key blocks but i am unsure on how to do this.
Current JSON file:
{
"blockID1": {
"name": "name here",
"locale": "en_GB"
},
"blockID2": {
"name": "name here",
"locale": "en_GB"
},
"blockID3": {
"name": "name here",
"locale": "en_GB"
},
"blockID4": {
"name": "name here",
"locale": "en_GB"
}
}
I just want to retrieve blockID3 and blockID4 and then I would output into another json file.
{
"blockID3": {
"name": "name here",
"locale": "en_GB"
},
"blockID4": {
"name": "name here",
"locale": "en_GB"
}
}
Does anyone have an example?
Use an array as a lookup and then loop over the object and if a key is found copy the value to the output object.
var obj = {"blockID1":{"name":"name here","locale":"en_GB"},"blockID2":{"name":"name here","locale":"en_GB"},"blockID3":{"name":"name here","locale":"en_GB"},"blockID4":{"name":"name here","locale":"en_GB"}};
var find = ['blockID3', 'blockID4'];
var out = {};
for (var p in obj) {
if (find.indexOf(p) > -1) {
out[p] = obj[p];
}
}
console.log(out);
Not sure if I understood your question but if you want to output something like that, and you have the ids of the json file if you want you could simply do something like this
const props = ['blockID3', 'blockID4'],
json = {"blockID1":{"name":"name here","locale":"en_GB"},"blockID2":{"name":"name here","locale":"en_GB"},"blockID3":{"name":"name here","locale":"en_GB"},"blockID4":{"name":"name here","locale":"en_GB"}},
res = {};
for(const prop of props) {
if(json[prop]) {
res[prop] = prop;
}
});
At the end res will have the objects that you wanted, hope this helps :)

Categories

Resources