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"];
Related
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
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
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I am trying to call Javascript's .map() method on a backbone collection that contains a JSON that looks like this:
[
{"from":"houston","to":"austin"},
{"from":"omaha", "to":"kc"}
]
My backbone model looks like this:
var ChoiceModel = Backbone.Model.extend({});
var choiceModel = new ChoiceModel({
a:'from',
z:'omaha'
})
The problem is every JSON document I'm interested in has the Key "from" instead of the city I'm interested in. Below I am trying to filter all the JSONs with the "from" value of "omaha".
var aVar = this.model.get('a');
var zVar = this.model.get('z');
return this.collection.map(function(model){
return {
a: model.get(aVar[zVar])
};
Ideally I would be able to later call variable 'a' it would only return: {"from":"omaha", "to":"kc"}.
I've tried a few variations of the code above to no avail. How can I .map() on JSON values?
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>"