How to iterate over JSON data - javascript

The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?

for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}

You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.

You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.

Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".

There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.

Related

How can I access a value in a multidimensional object with unique keys in Javascript?

How can I access the value for name in the object below? Also, does this object have a special name since unique keys (i.e. friend1 and friend2) hold other key/value pairs?
var friends = {
"friend1":{
"name":"ana",
"position":1,
"spouse":"billy"
},
"friend2":{
'name':'keri',
'position':2,
'spouse':'david'
}
};
Please note that this is a simplified version of the project I am working on. I realize there is a better way to hold data for a list of friends– the point to keep in mind is that the key that holds the other key/value pairs is unique.
I have tried this but it obviously does not work (i.e. "undefined"):
for( i = 0; i < Object.keys(friends).length; i++ ) {
var theFriend = [i].name;
alert(theFriend);
}
Here is a fiddle.
for(index in friends ) {
var theFriend =friends[index].name;
alert(theFriend);
}
Maestro please: https://jsfiddle.net/rwoukdpf/
In ES5, use:
for (var index in friends) { // NB: index and name have function scope
var name = friends[index].name;
}
In ES6, use:
for (let friend of friends) { // NB: 'of', not 'in'
let name = friend.name;
}
If you must use a normal for loop, ensure that your loop invariants are not evaluated in each iteration:
var keys = Object.keys(friends);
for (var i = 0, n = keys.length; i < n; ++i) {
var name = friends[i].name;
}
Even then this loop is not recommended, though - it's cheaper to use a single pass of the object with for .. in than to create an array of the keys and then iterate through that. The ES6 for .. of is better still.
Try following
var keys = Object.keys(friends);
for( i = 0; i < keys.length; i++ ) {
var theFriend = friends[keys[i]].name;
alert(theFriend);
}
For reference - https://jsfiddle.net/mu7jaL4h/7/
`[i]`
You've just created a new array and put the value of i in it.
You need to tell JavaScript what object you are accessing the i property of.
friends[Object.keys(friends)[i]].name

Loading JSON array from API into another array in Javascript using a loop

I'm pretty new to programming in general but have the problem that my array keeps being overwritten in my for loop so when I print in to the console only the last set of data is showing. i.e the data in the array is overwritten each time.
I want to store all the details in an array so I can work with the data. I have tried to put an array into an array but keep getting errors.
for (var i = 0; i < collection.length; i++){
var dailyfxTech = [];
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
How can I append the data to the dailyfxTech array each time it loops so that it looks like ;
dailyFxTech {[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], ...etc},
I later want to be able to reference the array to place the data in other parts of my site eg:
dailyFxTech[2,3] = the support of third ccy pair.
Thank you for your help.
Your issue is that each time the loop is running you are declariing a new array. Super simple fix. Just need to put the var dailyfxTech outside of your loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
Declare var dailyFxTech outside of the for loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
When you have the var declaration in the body of the for loop, the variable is re-allocated and the old value is trashed.

Javascript for loop alert value one by one

I have a trouble with looping the json array in JavaScript. How do I get only SG_J1001 and SG_LS01? Actually, I didn't get what I want. Result is come out like that [{"regis .......
var item = JSON.stringify(data['code']); //[{"registerCode":"SG_J1001"},{"registerCode":"SG_LS01"}]
for(var i=0;i < item.length; i++){
alert(item[i]);
}
Dont stringify, and use dot notation to access the property of each index:
for(var i=0;i < item.length; i++){
alert(item[i].registerCode);
}
Using jQuery you can do it like:
$.each(item, function(index,obj){
alert(obj.registerCode);
});
See EXAMPLE
Several correct posts here.
One more rendition:
for (var key in data.code)
alert(key.registerCode)

how to add properly the value of counter to a variable name

it can seems easy, but I'm little lost...
What I need is to add the counter value to a variable name.
for (var i=0; i<8; i++){
var upBt0; //this is the name in the first iteration
var upBt1; //this is the name in the second iteration
.
.
.
var upBt8; //this is the name in the last iteration
}
How can I do this properly?
Sorry, Daniel
EDIT:
for (var i=0; i<8; i++)
{
this.upBt = "upBt"+i;
this.upBt = new PL_Button().init("upBarButton"+i);
}
I create buttons...in particular 8 buttons...
And later, I need access to each of these buttons:
function (){
this.upBt1;
this.upBt1;
this.upBt3;
this.upBt6;
}
Hope have explained better.
EDIT 2:
Finally, I solved it using an auxiliar array of the class, where I pushed each object in each iteration. Each item of this array is a real reference to each object, so changed the item in the array, changes are also made in the corresponding object...
Hope have explained well.
Thanks for your help,
Daniel
You can use this, but it's ugly code...
for (var i=0; i<8; i++){
this["upBt" + i] = Object.create(null);
}
Use an array helped to me:
this._arrayButtons = {};
for (var i=0; i<8; i++)
{
this.upBt = new PL_Button().init("upBarButton"+i);
this.upBt.imgPath = "res/builder/"+upBarImgs[i];
.
.
.
this._arrayButtons[i] = this.upBt;
}
After, in one function, I can access to the content of the variables such as:
function refreshFrameAlpha(){
this._arrayButtons[3].alpha = 125;
this._arrayButtons[5].alpha = 225;
.
.
}
In this way, I can refresh alpha (p.e) of the object, because each item of the array is a reference to the corresponding object.

Building Array in forloop

I'm trying to create a basic for loop which creates an array but am a little confused in how to structure it... this is an example of the array:
var list = [
{id: "135", data: [9,129,345, 687]},
{id: "239", data: [596,382,0,687,33467]}
];
Those are just example numbers but i need to make it in a for loop (because the numbers come from variables, but i've got no idea how i do it =/
I know how to make a 1 dimensional array with a for loop but not anything this complex..
Does any one have an example loop to show how its structured?
EDIT: Just understood what you meant.
This is a bit of pseudo to show how you would create an array like the one in question
var list = [];
for(var i = 0; i < objectcount; i++){
// Here you need some way to get the ID for each should be dependant on 'i'
var obj = {id: 10, data: []}; object
for(var j = 0; j < datacount; j++){
// You need some way to retrieve each data number, dependent on 'j'
obj.data.push(somenumber)
}
list.push(obj)
}
OLD ANSWER
Assuming that you want to create an array of all the data arrays inside each object try something like this:
var newarray = [];
// This will iterate through each object in the list array.
for(var i = 0; i < list.length; i++){
// This will iterate though each value in the data array
// of the current list object
for(var j = 0; j < list[i].data.length; j++){
// Then you add that value to 'newarray'
newarray.push(list[i].data[j]);
}
}
Not sure if this is what you're asking, but to access the list object as shown you could
alert(list[0].id);
alert(list[0].data[0]);
and you would get 135 and 9 respectively.
Here's the for loops to see them all:
for (i=0; i<list.length; i++) {
alert (list[i].id);
for (j=0; j<list[i].data.length; j++) {
alert (list[i].data[j]);
}
}

Categories