I have a JSON array which is returned from my PHP ajax call. I need to loop through it and display all the information. I can not seem to get a method working. I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here.
my array is
[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]
The length of the array changes every time it is not always 6 items.
And the loop is going to go in my success handler. I just need help on how to access the data.
success: function(data){
}
You can use a simple loop statement:
success: function(data){
var i, l;
for (i = 0, l = data.length; i < l; i++) {
// access the object: data[i]
console.log(data[i]);
}
}
This is the most effiecient way.
You can just loop through the array:
success: function(data){
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var type = obj.Type;
var durable = obj.Durable;
var url = obj.Url;
// do work
}
}
You can use the array prototype forEach:
data.forEach(function(item) {
var type = item["Type"];
var durable = item["Durable"];
/*...*/
});
Related
I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all
I wanted to make a code that will easily save all variables. Normally i would need for 60 variables about 120 lines. Not very efficient. I decided to try to make one function with array to try to save all variables. It doesnt seem to work.
My problem is that loaded variables are string, but i need them to be float.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage[variablelist[i]] = window[variablelist[i]];
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage[variablelist[i]];
}
}
I have tried
window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];
Nothing has worked. It is still a string. Any ideas ?
First of all, it hurts me to see so much stuff stored on the window object like that. You should really give that a re-think!
LocalStorage is a way of storing a key-value pair to the browsers memory for access later. The only catch is that the value has to be a string.
You can get around this my using the JSON.stringify and JSON.parse function:
var objectToSave = {
key1: 'something',
key2: 'something else'
};
localStorage.setItem('myObject', JSON.stringify(objectToSave));
console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object
Otherwise, if you are set on saving all of the individual variables, you are not far off, you just need to use the getItem and setItem:
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], window[variablelist[i]]);
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage.getItem(variablelist[i]);
}
}
Use localStore.setItem() and localStore.getItem() to store and load items. Also use JSON.stringify() and JSON.parse() to convert objects to text, and then restore them back to objects.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
}
}
I am currently trying to get contents from a JSON object.
I've been looking all over google and what I think should work, for some reason, does not.
The JSON looks something like this:
{"locatie0":{"naam0":["Domplein"],"value0":["value1"]},"locatie1":{"naam1":["Neude"],"value1":["value1"]},"locatie2":{"naam2":["Vredenburg"],"value2":["value1"]},"locatie3":{"naam3":["Stadhuisbrug"],"value3":["value1"]},"locatie4":{"naam4":["Korte Minrebroederstraat"],"value4":["value1"]}}
I use below code to read the file but for some reason it will always return undefined or NaN.
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data.locatie[k].naam[k];
// Should alert "Domplein", "Neude", "Vredenburg", "Stadhuisbrug", "Korte Minrebroekstraat",
alert(_locaties);
}
}
});
Can anybody see if i've made any mistakes in my code or if there's a better way to read the values?
locatie[k] tries to access the property k of the object in locatie, but in your case, the number is part of the name itself. You have to build the property name dynamically. In addition, each property of the nested objects is an array with one element, so you have to access the first element:
var _locaties = data['locatie' + k]['naam' + k][0];
Your data structure is a bit strange though. The numbers in the property names makes accessing the data more difficult. If you can change it, change it to an array of objects and don't use arrays for the properties if you don't need them:
[{"naam": "Domplein", "value": "value1"}, {"naam": "Neude", "value":"value1"}]
Then accessing the data is simply:
for (var i = 0, l = data.length; i < l; i++) {
var _locaties = data[i].naam;
}
A JSON does not guarantee any order like an array.
But in your case, the keys of the JSON have index hints, so try accessing "naam" with:
data["locatie" + k]["naam" + k]
Try this:
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data['locatie'+k]['naam'+k][0];
alert(_locaties);
}
}
});
As the value of naam property is array you need to fetch first item from it in order to get string value.
The locatie and the naam are not arrays, so you cannot access them like the way you do.
You have to combine the number with the name as a string. Something like that
data['locatie'+k]
try this ;
k = 0;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
k = 1;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
I have an object in my javascript which looks like this:
{"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}},
// .....
What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently.
I have an array for longitude, latitude, color and level.
So I have tried the following:
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
alert(result.data[size]);
}
-->But this only alerts me "[object Object]"
success: function(result){
var size = 0, key;
for (key in result) {
for(var attr in key){
alert(attr['latitude']);
}
}
}
-->This gives me Undefined result[key]
I have checked that the size of my object is only 1 thru these codes
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
}
alert(size);
I believe that only "data" is being read. And others that are inside "data" are disregarded.
I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.
UPDATE
Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched
t
Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color "#040098"
latitude "14.6204083333333"
level "35"
longtitude "121.0508"
I tried this
for (key in result) {
if (result.hasOwnProperty(key)) size++;
console.log(result.data[size]['level']);
}
--> but it says undefined
based on the structure of my object which is
data:[{"t":{'others'},'others'...]
How am I to read everything inside "data"? Each "data" has "t".
Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):
for(var i=0; i<results.data.length; i++){
alert(results.data[i]['t']['latitude']);
// etc...
}
Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
var latitudes = [];
// and so on...
for (var idx in result.data ) {
if( result.data.hasOwnProperty(idx) ){
alert( result.data[idx]['t']['latitude'] );
// So you would do something like this:
latitudes.push ( result.data[idx]['t']['latitude'] );
// and so on...
}
}
}
Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.
var latitudes = $.map( result.data, function(n){
return n['t']['latitude'];
});
// and so on...
Assuming result is your object, this should just be a matter of iterating over your data array:
for (var i = 0; i < result.data.length; ++i) {
console.log(result.data[i].t.latitude);
...
}
It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?
var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}}
]};
var data = result.data;
var i, len, t;
for (i = 0, len = data.length; i < len; i++) {
t = data[length].t;
levels[i] = t.level;
longitudes[i] = t.longtitude;
latitudes[i] = t.latitude;
colors[i] = t.color;
}
See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.
var data = input.data,
result = {level: [], longtitude: [], latitude: [], color: []};
for (var i = 0, n = data.length; i < n; i += 1) {
var info = data[i].t;
for (var property in info) {
if (info.hasOwnProperty(property)) {
result[property].push(info[property]);
}
}
}
console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);
This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']