Trouble extracting data from 2D array jQuery - javascript

I have used Ajax to run a PHP script to return records in a database. I have managed to retrieve the 2D array into my JavaScript file on the success of the Ajax call. I then call a function.
In the function I would like to pull the data from the arrays and save them into JavaScript variables.
I am using jQuery, so I assume I have to use $.each?
Here is the response I am receiving back from the ajax call:
[{"level":"1","location":"4554","quantity":"2","game_item_id":"1"},{"level":"1","location":"4554","quantity":"1","game_item_id":"5"}]
What I am trying to do is extract the level, location data from this 2D array and save it into level and location variables in JavaScript.
Also as you can see the two records being sent back are identical except the game_item_id and the quantity. I want to save a list of the game_item_ids and their associated quantity values into an array or variable.
EDIT
Thanks to answers i have managed to save the level and location data into variables. But im still stumped on how to store each game item id and the quantity of each?

say your object is named data...use loop
$.each(data,function(i,v){
console.log(v.level);
console.log(v.location);
})

Hi refer below code to get id and quantity in array ::
var list =
[{"level":"1","location":"4554","quantity":"2","game_item_id":"1"},{"level":"1","location":"4554","quantity":"1","game_item_id":"5"}];
var arrGameIdAndQuantity = new Object();
for(i=0;i<list.length;i++){
id = list[i]["game_item_id"];
qty = list[i]["quantity"];
arrGameIdAndQuantity[id] = qty;
}
alert(JSON.stringify(arrGameIdAndQuantity))

what about this ;
data[1].level
You can loop through each array like this
data = $.parseJSON(data); // if data is not in json
$.each(data, function(item, value) {
alert(value.level);
alert(value.location);
alert(value.game_item_id);
alert(value.quantity);
});

Related

How to assign more than one value to a key in Object.assign

I am using Object.assign method to change the structure of my JSON.
let opVal = []
data[item].map(function(key,value) {
opAllVal = key;
finalResult = Object.assign(data, {[item]: [opAllVal]});
});
Here data contains the JSON. And key contains more than one value at a time. I want to send all the values that are coming in key in the below format.
For e.g., If item is sampleKey and values in key are sampleValue1 and sampleValue2, so they should be sent as -
"sampleKey":["sampleValue1","sampleValue2"]
but with the above code, these are sending as -
"sampleKey":["sampleValue2"]
Only the last value is getting sent everytime, not all the values which are coming in key. Can anyone help me in sending all the values of key to item in the above format.
Thanks in advance...
Every time you use the code finalResult = Object.assign(data, {[item]: [opAllVal]});, you are overwriting the previous version of data[item] ignoring the previous content, in other words, data[item] is always set to an array with a single element that is key.
Btw, by the code it's not very clear what you'd like to do. If I understood you can have an input like this:
data = {
... //other params
"sampleKey": [
"sampleValue1",
"sampleValue2"
]
}
What's the expected output?
For what I see in the code it will be better to use forEach instead of map and the name of the variables in forEach should be inverted (value, key) instead of (key, value) as map and forEach call both the callback by passing before the value and after the key.
Also I suggest to change the tag in your question as it is not related to reactjs but it's related to js and independent from react (if you do this you'll receive more visualisations and more answers).

Javascript in HAML in Javascript

I've got a question that mightve been asked before but i have trouble finding a proper description. I hope someone can help me out.
In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. How do I do this in embedded rails in javascript?
:javascript
$('#accu').change(function() {
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = "#{currency(Product.find_by(id: accu_id).price2)}"
$('#price_accu').append(price)
});
Or is there an easier way to do this?
You have two options.
You can use AJAX request to get data from database
You can use mapping concept like following
var data = #processed_data // json data, which contains processed data in json format.
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = data.accu_id;
Here the #processed_data contains data like following
#processed_data = currency_calculation
def currency_calculation
Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json
end
Example
Assume products table have two entries then the #processed_data contain values like following
{ "1" => "20.00", "2" => "25.50" }
The above data directly assigned to js variable data and accessed like data.key
The first option is best choice and second is possible one.
Note : You can't use js variable inside ruby.

How to retrieve value from json of one array and one int literal in javascript

I am passing data back to java script through a rest api. The rest API return data in the following below mentioned structure.I am confused what format of json is it and how can i iterate on the array inside and get the int value individually.
The format of my response is like :
{"searchOrder":[
{"location":"10","trackingId":"656"},
{"location":"34","trackingId":"324"},....],
"count":100}
i want searchOrder as array of json to display in table and count to show total row.How can i get them?
Just iterate over the array and extract the values
// Turn the JSON into a JS object (maybe in your XHR handler)
var data = JSON.parse(jsonString); // jsonString could be responseText from XHR
var arrayOfTrackingIdValues = data.searchOrder.map(function (value) {
return value.trackingId;
});
JavaScript provide built-in function JSON.parse() to convert the string into a JavaScript object and drive/iterate the each element based on type obj/array
var obj = JSON.parse(text);

Javascript read text file and append values to array

I have a problem with populating a JavaScript array with a function...
I have some charting software that uses JavaScript. I can input my own values into an array directly to create my desired chart like so:
var data_array=[[0,170],[0,185],[0,179]]
The first value in the array corresponds to sample number (e,g, 0) and the second value corresponds to height (e.g. 170, 185 etc).
This works but I will eventually have a huge list of thousands of values. The height values will be stored in text files. There will be a different file for each sample. The text file will contain a simply list of values separated by lines.
What I need my program to do is open a text file and extract the values and then append them to the data array. So far I have this:
$.get('sample0.txt', function(data, data_array){
var lines=data.split('\n');
for (var i=0; i<lines.length-1;i++){
var item=lines[i];
data_array.push([0,item]);
}
return data_array
}
This doesn't work, although I know it is correctly extracting the values from the text file. I'm not worried about sample number as I can set this for each file. My problem is how to populate the array and make that array exist outside of the function.
I normally code in PHP and I apologize that my knowledge of JavaScript is very basic!
// set this somewhere outside of the $.get callback.
// no need to pass it in as it will be available in that scope.
var data_array = [];
$.get('sample0.txt', function(data) {
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]); // modify data_array here
}
// no need to return it
});
Here's a very reduced test: http://jsfiddle.net/4GMMd/
Also note no -1 after lines.length in your for loop, unless your files end with a blank line that you don't want to read.
If I understand your question correctly, you just need to declare the data_array outside the scope of your request function. Plus, your loop is incorrect. It should be i<lines.length not lines.length-1 unless you intend to leave out the last line.
var data_array = [];
$.get('sample0.txt', function(data){
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]);
}
}

Parsing a JSON feed from YQL using jQuery

I am using YQL's query.multi to grab multiple feeds so I can parse a single JSON feed with jQuery and reduce the number of connections I'm making. In order to parse a single feed, I need to be able to check the type of result (photo, item, entry, etc) so I can pull out items in specific ways. Because of the way the items are nested within the JSON feed, I'm not sure the best way to loop through the results and check the type and then loop through the items to display them.
Here is a YQL (http://developer.yahoo.com/yql/console/) query.multi example and you can see three different result types (entry, photo, and item) and then the items nested within them:
select * from query.multi where queries=
"select * from twitter.user.timeline where id='twitter';
select * from flickr.photos.search where has_geo='true' and text='san francisco';
select * from delicious.feeds.popular"
or here is the JSON feed itself:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20query.multi%20where%20queries%3D%22select%20*%20from%20flickr.photos.search%20where%20user_id%3D'23433895%40N00'%3Bselect%20*%20from%20delicious.feeds%20where%20username%3D'keith.muth'%3Bselect%20*%20from%20twitter.user.timeline%20where%20id%3D'keithmuth'%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=
I am using jQuery's $.getJSON method
You don't need to parse JSON by hand. That's the point of JSON. Use JSON.parse(yourJSONstring) to convert it into a Javascript object.
Edit: Actually I'm not sure the browser support for that one. Here's the jQuery way:
http://api.jquery.com/jQuery.parseJSON/
Edit2:
var results = feedObj.query.results.results
for (var i = 0; i < results.length; i++) {
if (results[i].photo) {
// do something with photos
} else if (results[i].item) {
// do something with items
} else {
// do something with entry
}
}
Test for the existence of the results[i].photo object. If it exists, the result is an array which you can loop through and do something with.

Categories

Resources