I have a dynamic string variable created by UI (valkey in below code) and I want to use that variable as a JSON key to get a value from TestObj which is a JSON object. But an attempt with the following code has returned an error.
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL")
{
$.each(TestObj.valkey, function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}
I appreciate any help.
TestObj.valkey will look for the key valkey in TestObj, which is undefined in your case that is why you are getting the error.
If you want to look for a key from a variable you need to use the syntax TestObj[valkey].
Ex:
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL") {
$.each(TestObj[valkey], function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}
Related
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
Hi I have a json response that I have to parse. I want to pull the data and insert it into inputs value (if it exists)
My json is like this:
{"id":4,"comb_name":"Monitor__C9cGTqnM7Trz","resolution":null,"attribute_val":3,"porte":4, "deleted_at":null,"created_at":"2017-11-13 10:10:25","updated_at":"2017-11-13 10:10:25"}
The code:
if(isset(jsobj)) {
var parsed = JSON.parse(jsobj);
console.log(parsed);
for (var property in parsed) {
if(parsed.hasOwnProperty(property)) {
var possible_input = '#pro_' + property;
if($(possible_input).length) {
var actual_input = $(possible_input);
actual_input.val(property);
}
}
}
}
It actually works, the only problem is that "property" are "attribute_val", not "3". What can I do to grab the value of the property?
Just use the property name to access the value
actual_input.val(parsed[property]);
I am dynamically creating a row using javascript, here is the code below:
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+name+" data-toggle='modal'>Edit</a></td></tr>";
The var here is a JSON object. This is later passed onto the modal when a user clicks it and values can be retrieved. However, simply declaring var like I have done above sets data-info=[Object object].
The content of the JSON variable is:
Object
name: "Test 8"
created_at: "2015-06-10 16:54:45"
id: 128
updated_at: "2015-06-10 16:54:45"
__proto__: Object
Is there a way around it?
Some advice here:
Don't use var as a variable name, even in examples (real code won't even compile)
Please, make sure you understand what JSON is, because Javascript object != JSON. Clearly var is a JS object in this case.
Said that, you can transform any JS object that does not contain functions into a JSON string with JSON.stringify(variable):
UPDATE: This is what I mean:
var row2 = '<tr><td><a href="#editModal" class="modal_trigger" data-info="'+
name+'" data-toggle="modal">Edit</a></td></tr>';
(Note the changes using quotation marks)
If you get [object Object] then it is not a JSON, is an Object.
JSON is a string containing an object serialized, and it is used as a lightweight data-interchange format.
Try serializing the object to JSON
"...data-info=" + JSON.stringify(myVar||null) + " data..."
Here I added coercion to null to prevent an error when the variable contains no data.
please Use JSON.stringify(yourVar).
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+JSON.stringify(yourVar)+" data-toggle='modal'>Edit</a></td></tr>";
Store your name variables in some mapping or array, store the id or the index in your row, and use this to fetch it back later :
// using a mapping :
var infoMapping = {};
function createRow (name) {
// this will work if 'id' is a key which identifies the object
infoMapping[name.id] = name;
var row2 = "<tr><td><a href='#editModal' ... data-infoid="+name.id+" ... ";
// etc ...
}
function editModal (nRow) {
var infoid = $(nRow).attr('data-infoid');
var name = infoMapping[infoid];
// use name ...
}
var x = {a:10, b:20};
var html = "<div data-info='" + JSON.stringify(x) + "'></div>";
Result is
"<div data-info='{"a":10,"b":20}'></div>"
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I am creating a "Garment checker" using ajax and I would like the user to put the ID into the input followed by a request to the URL. which prints out the code if it exists. The code below just isn't doing the job as I would like it to although I think that it is almost correct. Can anybody see my mistakes or point me in the right direction please?
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
"use strict";
$('#lookupForm')
.removeAttr('onsubmit')
.submit(function(event) {
event.preventDefault();
var target = document.getElementById('garmentID');
if(target.value.length > 0) {
fetchData(target.value);
}
});
});
function fetchData(garmentID) {
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
$.getJSON(url, function(data) {
var appDetails = data.AvailableSkus[0];
$('#garmentTitle').val(appDetails.AvailableSkus);
});
}
//]]>
</script>
Since data.AvailableSkus seems to be an array, you don't want to pass the collection as the value to #garmentTitle.
You're most likely after a property (if the array contains objects) or the actual element:
//if typeof appDetails.AvailableSkus[0] is string or number:
$('#garmentTitle').val(appDetails.AvailableSkus[0]);
or
//if typeof appDetails.AvailableSkus[0] is an object:
$('#garmentTitle').val(appDetails.AvailableSkus[0].someProp);
value
Type: String or Array
A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
This link provides output properly
http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=5
are you sure "applicationID" is setted before ?
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
Any error message in firebug console ?