Hi this is my JsonObject i want to iterate this and get the values of title elements class of header , Container and footer.
var jsonObj = [{
"Header": {
"title": "Header",
"element":"div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Container": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Footer": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable": "true"
}
}]
You can do this by
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " -> " + jsonObj[0][key].title);
}
}
Here id the fiddle for this code.
For getting the inner elements from the object we have to extend the previous loop
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " ---");
for(innerKey in jsonObj[0][key]) {
console.log(innerKey + " -> " + jsonObj[0][key][innerKey])
}
console.log("-----")
}
}
Here is the fiddle for above code
Related
I want to get the array value in separate comboboxes using JavaScript and PHP. Suppose i have array like
0:{"id":"none","name":"none"},1:{"id":"none","name":"none"},2:{"id":"write","name":"write"}
I want that 0 index array will show in first combo box, 1 index array will show in 2nd combo box and so on, all combo boxes having same name. But when I done it is showing all arrays in one combo box .Here is my code
var data = [{
"id": "none",
"name": "none"
}, {
"id": "none",
"name": "none"
}, {
"id": "write",
"name": "write"
}]
$.each(data, function(i, item) {
$('#modules').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="modules"></select>
You want 3 dropdowns?
var data = {
"one": [{ "id": "none", "name": "none 1" }, { "id": "none", "name": "none 1" }, { "id": "write", "name": "write 1" }],
"two": [{ "id": "none", "name": "none 2" }, { "id": "none", "name": "none 2" }, { "id": "write", "name": "write 2" }],
"three": [{ "id": "none", "name": "none 3" }, { "id": "none", "name": "none 3" }, { "id": "write", "name": "write 3" }]
}
$.each(data, function(i, item) {
var $sel = $("<select/>", {
"name": "data"
});
$.each(item, function(i, selItem) {
$sel.append('<option value="' + selItem.id + '">' + selItem.name + '</option>')
});
$('#modules').append($sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modules"></div>
If you wanted to achieve this using plain JavaScript, please see below snippet with desired output - select dropdown with text from objects in array populating the options.
var data = [{
"id": "none",
"name": "none"
}, {
"id": "none",
"name": "none"
}, {
"id": "write",
"name": "write"
}]
function comboBox(data) {
const select = document.getElementById('modules')
data.map(object => {
let option = document.createElement("option");
option.value = object.id;
option.text = object.id;
select.appendChild(option);
})
}
comboBox(data);
<select id="modules"></select>
i think you want to show data in dropdown
just make sure your array is in correct format.
var data = [{"id":"none","name":"none"},
{"id":"none","name":"none"},
{"id":"write","name":"write"}];
$.each(data,function(i,item){
$('#modules').append('<option value="'+data[i].id+'">'+data[i].name+'</option>'); });
$('.modules').eq(i).append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
full json is
{
"id": "70dec1ac-345f-4b94-b255-b09c5ab1b522",
"name": "card",
"auto": true,
"contexts": [],
"responses": [
{
"resetContexts": false,
"affectedContexts": [],
"parameters": [],
"messages": [
{
"type": 1,
"platform": "facebook",
"title": "this is the title updated",
"subtitle": "this is the subtitle",
"imageUrl": "https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg",
"buttons": [
{
"text": "this is the button"
},
{
"text": "this is also a button"
}
],
"lang": "en"
},
{
"type": 0,
"speech": []
}
],
"defaultResponsePlatforms": {},
"speech": []
}
],
"priority": 500000,
"cortanaCommand": {
"navigateOrService": "NAVIGATE",
"target": ""
},
"webhookUsed": false,
"webhookForSlotFilling": false,
"lastUpdate": 1530197695,
"fallbackIntent": false,
"events": [],
"userSays": [
{
"id": "528c22d4-49d7-4ab9-a8db-fcd84d57694b",
"data": [
{
"text": "card"
}
],
"isTemplate": false,
"count": 0,
"updated": 1530196620,
"isAuto": false
}
],
"followUpIntents": [],
"templates": []
}
I am actually making a chatbot for wordpress to communicate with api.ai or dialogflow
The code I am currently using to display a card is the following:
var html = "<div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-image-response\"><img src=\"" + imageUrl + "\"/></div>";
html+="<div class=\"myc-card-title\">" + title + "</div>"
html += "<div class=\"myc-card-subtitle\">" + subtitle+ "</div>";
html += "<input type=\"button\" " + "style=\"background-color:rgb(221, 153, 51);text-transform: none\"" + "class=\"myc-quick-reply\" value=\"" +buttons[0]+ "\" />";
var innerHTML = "<div class=\"myc-conversation-bubble-container myc-conversation-bubble-container-response\"><div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-quick-replies-response\">" + html + "</div>";
I am getting the image ,title ,subtitle correctly but the Button is displayed as [object Object] what is the correct way to do it?
The button text is in the text property.
Try to replace buttons[0] with buttons[0].text.
in your case buttons is an array of object and have property text. so try buttons[0].text
I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/
I have a JSON DATA like the following
[
{
"name": "car",
"value": "",
"children": [
{
"name": "v8_engine",
"value": "",
"children": [
{
"name": "cylinder-arrangement",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": []
},
{
"name": "max-elements",
"value": "8",
"children": []
}
]
}
]
},
{
"name": "other-parts",
"value": "",
"children": [
{
"name": "per-cylinder-parts",
"value": "",
"children": [
{
"name": "piston-diameter",
"value": "",
"children": [
{
"name": "type",
"value": "uint32",
"children": []
},
{
"name": "range",
"value": "2000... 9000",
"children": []
}
]
},
{
"name": "valves",
"value": "",
"children": [
{
"name": "number",
"value": "",
"children": []
},
{
"name": "position",
"value": "",
"children": []
}
]
}
]
}
]
}
]
}
]
I want to parse through each elements and their respective childrens and list them out as parent children and their grand children like a simple tree in GOJS.
I am using the following logic but that just parses and pushes node data and link data array element in go-js model.
var i=0;
function loop(a) {
if(a.yang_type!='' && a.name!=''){
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name, group: -1 });
console.log("Data:",a.yang_type);
linkDataArray.push({ from: i, to: i+1 });
}
if(a.name!='' && a.value!=''){
nodeDataArray.push({ key:i,Data: a.name + " " + a.value, group: -1 });
linkDataArray.push({ from: 0, to: i+1 });
}
//console.log(a.name);
i=i+1;
// process you data
Array.isArray(a.children) && a.children.forEach(loop); // check and iterate children
myDiagram.model = go.GraphLinksModel(nodeDataArray, linkDataArray);
}
Attached is the output that i am getting but the childrens are cluttered. Am I missing some logic in pushing?
I suggest that you use a GoJS TreeModel rather than a GraphLinksModel. http://gojs.net/latest/intro/usingModels.html
Take a look at the DOM Tree sample, http://gojs.net/latest/samples/DOMTree.html. Note in particular the traverseDom function. TreeModels expect to have a reference from the child data to the parent data. HTML DOM, like your data parsed from JSON, has the references to the children in an Array in the parent data. That sample's traverseDom function makes sure each data object has a key that is a number or a string and then assigns the child's parent property to that key value.
You can then use an Array of those objects as the TreeModel.nodeDataArray.
var nodeDataArray = [
{isGroup:true,key:-1,text:"Service Parameters",xy:"210 31.999999999999996"},
{ isGroup: true, key: -2, text: "Device Model", xy: "435 36.000000000000014"}
];
var linkDataArray = [];
var i=0;
function loop(from) {
return function (a) {
var f = i;
if(a.yang_type!='' && a.name!=''){
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name, group: -1 });
//c=c+a.name;
//console.log("c:",c);
//console.log("Data:",a.yang_type);
//linkDataArray.push({ from: i, to: i+1 });
}
if(a.name!='' && a.value!=''){
nodeDataArray.push({ key:i,Data: a.name + " " + a.value, group: -1 });
//c=c+a.name+a.value;
console.log("c:",c);
//linkDataArray.push({ from: 0, to: i+1 });
}
if (from !== undefined) {
linkDataArray.push({ from: from, to: i });
}
i++;
if (Array.isArray(a.children)) {
a.children.forEach(loop(f));
}
//console.log("c:",c);
};
}
I want jQuery to make new ul for each set of products.
Inside of each ul, all items of each set will be appended.
The result was unexpected; there should be only 2 ul, but
11 ul were appended.
My jQuery
$.getJSON('/products.json', function (result) {
var booksobj = result.ebooks.basic;
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
});
});
products.json
{
"ebooks": {
"basic": {
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
],
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
]
}
}
}
Thanks in advance.
You're looping over set and for each item inside a set, you're creating a new ul element. You need to have multiple loops where you create an ul and afterwards add all the lis for the section. I changed your data structure, you don't need the set properties (and they're overriding each other as property names are unique). basic is now an array which consists of arrays which represent a set.
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
data.ebooks.basic.forEach(function(set) {
var $list = $('<ul></ul>');
set.forEach(function(pdf) {
$list.append('<li>' + pdf.title + '</li>')
});
$('#ebook').append($list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ebook"></div>
It looks like the problem stems from the selectors in this snippet:
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
The selector "$('#ebook ul')" won't select the newly added ul in the iteration, instead it'll append to the first match (so the first ul added to the #ebook div). Instead, try chaining your calls like so:
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>').append('<li>' + item.title + '</li>');
});
Working example with JSON data in a variable: http://codepen.io/JasonGraham/pen/WxbvRo
Your problem is use $('#ebook ul'), another question, why you use the key "set" two times? No make sense,
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
$.each(data.ebooks.basic, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$.each(item, function(i, item2) {
$('#ebook ul:last').append('<li>' + item2.title + '</li>');
});
});
see the fiddle