I have a JSON being returned an I want to take the last 8 elements of the JSON and make a table. The table builds the way I expect it to but I'm getting undefined as the result value.
Here is the code for the getJSON, an edited down return and the table.
$.getJSON("loadloads.php", function(data){
[{
"value": {
"lineNumber": "258640",
"TypeId": "1",
"StopNumber": "1",
"ReferenceNo": "0002325063",
"LocationId": "3",
"SLN": "227311",
"LoName": "Elk GAF Materials Corp - Shafter",
"Type": "Shipper"
}
}, {
"value": {
"lineNumber": "258641",
"TypeId": "2",
"StopNumber": "2",
"ReferenceNo": "682383",
"LocationId": "205697",
"SLN": "227311",
"LoName": "RWC Building Products - Albuquerque",
"Type": "Consignee"
}
}
]
var table_obj = $('table');
$.each(data, function(index,value){
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
The name you gave your variable "value" is confusing you. You still need to reference the "value" key within your object that just happens to be named value.
'+value.value.SLN+
Try this way .
value.value.SLN
Try this. All properties are inside value so you should try value.value
$.each(data, function(index, v){
var value = v.value;
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
}
try this
for (var i in data)
console.log(data[i].value);
if it will output in console result, just use it as data[i].value.field
Related
I was trying to show my json data using jquery.each().
now this is the json
var json =
[
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"
}]
then i can show it
$.each(json, function(idx, obj) {
alert(obj.tagName);
});
But my json is
{
"Message": "Success",
"Code": "200",
"Payload": [
{
"year": "2015",
"month": "6",
"fileCount": "985",
"totalFileSize": "2820"
},
{
"year": "2015",
"month": "7",
"fileCount": "15347",
"totalFileSize": "66549"
}
]
}
Now I need to read the data inside the Payload. please help me with
Very simply. Payload is property of the object that you have provided, which can be accessed like this: json.Payload. So you should pass it as the first argument to $.each() method. Here you go:
$.each(json.Payload, function(idx, obj) {
console.log(obj);
});
http://jsfiddle.net/2wxwkxbd/
You can also use
$.map(array,function(obj,index){
console.log(obj)
});
for iterating through an array
I'm trying to add data to the end of an observable array but it's just not working as expected. I bet it is something minor but I just can't get my head around it.
What I am doing:
self.businesses = ko.observableArray();
function Business(business) {
var self = this;
self.BusinessID = ko.observable(business.BusinessID );
self.Type = ko.observable(business.Type);
self.Location = ko.observable(business.Location);
}
/*ajax get array of businesses as follows:
[
{
"$id": "1",
"BusinessID ": 62,
"Type": "Data",
"Location": "Data"
},
{
"$id": "2",
"BusinessID ": 63,
"Type": "Data",
"Location": "Data"
},
{
"$id": "3",
"BusinessID ": 64,
"Type": "Data",
"Location": "Data",
} ]
*/
var mappedBusinesses = $.map(data, function (business) { return new Business(business) });
self.businesses(mappedBusinesses);
This all works as expected and the obersablearray is populated.
However if I go to add another business, it wont work. For example, if I call the ajax that returns this (as newBusiness):
{
"$id": "1",
"BusinessID ": 68,
"Type": "Data",
"Location": "Data"
}
and I do:
self.businesses().push(newBusiness);
It adds to the array as an "Object" not a Business. So I thought I would do:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
But I get the error in the JS console "Uncaught TypeError: Cannot read property 'BusinessID' of null
So I made a new var and added the brackets: [] in and it adds to the observable array but not as a "Business" object but rather as an "Array[1]" object at the end and this doesn't function as per the others. Code as follows:
var newBus = {
BusinessID: newBusiness.BusinessID,
Type: newBusiness.Type,
Location: newBusiness.Location
}
var bus = $.map(newBus, function (business) { return new Business(business) });
self.businesses().push(bus);
As mentioned this adds to the observable array but doesn't actually add as a "business" object but rather as an "array[1]" object.
I bet it's something so basic but just can't get it working!
Argh I knew it would be simple!
It was posting the whole array to the ObservableArray...not just the object.
The fix:
self.businesses.push(newBusiness[0])
Had to add the [0] in to get it to push the actual data into the array, not the object!
Thanks for the answers!
You're evaluating the array with your push:
self.businesses().push(newBusiness);
Observable Arrays have their own array functions, you should just do this (no parens):
self.businesses.push(newBusiness);
See this page: http://knockoutjs.com/documentation/observableArrays.html
I'm hitting an api built using CakePHP. Cake returns its objects like this:
[
{
"Note": {
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
}
},
{
"Note": {
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
}
]
What I want to do is take that result and basically get rid of the keys. Something like this:
[
{
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
},
{
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
]
I'm basically just trying to make it easier to reference this in Angular. I need to do this on the client side. Any ideas?
You could refactor it like so:
var json = '[{"Note":{"id":"1","clas":"test","obj_id":null,"note":"test"}},{"Note":{"id":"2","clas":"another","obj_id":null,"note":"another"}}]';
var obj = JSON.parse(json);
var arr = [];
for (i = 0; i < obj.length; i++)
{
arr.push(obj[i].Note);
}
Working example here
(Note also that if your key value 'Note' isn't always the same, this will change dramatically. It's likely that 'Note' isn't going to be the same in each instance either; that would generate an improperly keyed object. Alternatively, if you always need the first object in the array, you could use obj[i][0] instead).
(More note if you're using cakephp, this would be much easier done using Hash::, but if you need to do it client side, this is the solution).
This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck
I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?
This is example of my JSON, can be much longer.
[
{
"id": "1",
"name": "test"
},
{
"id": "1",
"name": "test"
}
]
HTML:
<select id="sel">
</select>
JavaScript:
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
Here's a working example. http://jsfiddle.net/ms2Ma/
Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.
You need to follow few steps:
Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.
Here is the data:
var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
var Data ={"phones":[
{
"oid":":000000F0:00000458:",
"level1":"3G",
"level2":"white",
"level3":"16GB",
"level4":"slim",
"level5":"Back cover",
"level6":"headphone",
"price":"£568.63",
"addToCart":"#Cart1"
},
{
"oid":":000000F0:000003DA:",
"level1":"3G",
"level2":"black",
"level3":"16GB",
"level4":"slim",
"level5":"Flip cover",
"level6":"headphone",
"price":"£615.79",
"addToCart":"#Cart7"
}]};
See the full working code here:
https://jsfiddle.net/raju_sumit/681ppgq0/5/
Try this :)
Javascript:
$.getJSON("/array.json",
function (json) {
$.each(json,
function (key, value) {
$("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
});
});
A pure Javascript solution: this snippet shows how to populate a dropdown select from JSON data (using id as value and name as text.
The code creates a new Option object for each item in the JSON data and appends it to the select element with appendChild(). map is used in place of a for loop.
let data = [{
"id": "1",
"name": "name_1"
},
{
"id": "2",
"name": "name_2"
}
];
var selectElement = document.getElementById('mySelect');
data.map(item => mySelect.appendChild(new Option(item.name, item.id)).cloneNode(true));
<select id="mySelect" onchange="alert(this.value)"></select>