Javascript access json data inside loop - javascript

I have json data, now I'm trying to access it inside loop. But I got undefined.
Is there any way how to access it from loop?
var list = {
macAddress: 'C0:49:EF:D3:79:20',
category: 'esd',
dr1: 1,
dr2: 1,
dr3: 0,
dr4: 0
}
console.log(list);
for(var i=1; i<=2; i++) {
var pinName = "dr" + i;
console.log(list.pinName);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

List has no property pinName. You need the value of pinName to be evaluated as the key by calling list[pinName].

Related

Issue with object property '0' of undefined

My code yields the following error:
Uncaught TypeError: Cannot set property '0' of undefined
First, here's the screenshot of the table
Note:
This table are the assigned work schedule of the student.
Let's proceed to my code:
function saveWorkSched(){
// listWorkSched
var arr=[];
var getSAWorkSched=[[],[]];
var wsCounter=0;
var wsCounter2=0;
var j = 0;
$("#listWorkSched td").each(function(){
arr.push($(this).text());
});
console.log(arr);
for(j;j<arr.length;j++){
if(wsCounter2<=2){
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}
}
}
1st phase:
after the user create the work schedule this will be stored in arr variable.
2nd phase:
the arr value will converted to multi-dimensional array and will be stored in getSAWorkSched variable
after the 3rd loop an error will occurred. it means that every time I create a work schedule more than 2 the error will trigger.
else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j]; // Here's the code where the error specified based on the console of my browser
wsCounter2++;
}
You need to define the nested array that you try to access. It really comes down to the same principle: you address the following:
getSAWorkSched[wsCounter][wsCounter2]
... with a wsCounter value that is eventually getting to 2, but you have only defined two nested arrays in the initialisation of getSAWorkSched, so getSAWorkSched[2] does not exist -- it will give you undefined. Trying to get an array element from nothing (undefined) is not possible. So add this line before it in the else bock:
getSAWorkSched[wsCounter] = []; // <--- Add this
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
More elegant code
You could use $.map and slice to write this in a more elegant way:
function saveWorkSched() {
var arr = $.map($("#listWorkSched td"), function (td) {
return $(td).text();
});
var getSAWorkSched = [];
for (var j = 0; j < arr.length; j += 3) {
getSAWorkSched.push(arr.slice(j, j + 3));
}
}

Accessing an object inside of an array inside of an object in javascript

I'm trying to write a function that accesses an object inside of an array inside of an object and then push that into an array.
This is the code I have right now:
Javascript
stuff: function (index1, index2) {
for (var i = 1; i < index1.length; i++) {
state[index2].push(foodData[index1][i].name);
}
}
When I run storage.stuff('ingredientsToInclude', 'desired') I get the following error:
Cannot read property 'name' of undefined
However, if I access foodData["ingredientsToInclude"][1].name in the console it returns the correct value.
Not sure the reason for the discrepancy.
you are looping over string 'ingredientsToInclude' instead of actual array foodData['ingredientsToInclude'].
So change for (var i = 1; i < index1.length; i++) { to for (var i = 1; i < foodData[index1].length; i++) {

Loop through JSON array in Javascript

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"];
/*...*/
});

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]);
}
}

With javascript, is it possible to define a variable's name with another string value?

Example, I have an array called 'categories' with the value ['4','9']. I'm trying to use that value with the name of a previously defined array. I have several arrays defined earlier called row1, row2, row3 etc. I'm also using jQuery.
Trying to do something like this:
for (i=0; i<categories.length; i++) {
row+categories[i].push($(this).attr('id'));
console.log(row+categories[i]);
}
Obviously row+categories[i] doesn't work, but maybe gives you an idea of what I'm trying to do? In this case to push that id value onto the array 'row4' the first time it loops through and then 'row9' the second time.
Thanks for your help!!
Rather than defining multiple row1, row2, row3 etc., why not define a single rows variable that contains multiple arrays?
var rows = [[], [], []];
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
rows[categories[i]].push($(this).attr('id'));
console.log(rows[categories[i]]);
}
It could even be an object with properties if that makes sense in your situation:
var rows = {
row1: [],
row2: [],
row3: [],
getRow: function(index) {
return this["row" + index];
}
};
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
rows.getRow(categories[i]).push($(this).attr('id'));
console.log(rows.getRow(categories[i]));
}
You can use eval(), even if i don't like it personnaly...
for (i=0; i<categories.length; i++) {
eval("row" + categories[i] + ".push($(this).attr('id'))");
console.log(eval("row" + categories[i]));
}
do you want a global or local variable? (the code below uses global variables)
var rowVar;
for (i=0; i<categories.length; i++) {
rowVar = "row"+categories[i];
window[rowVar].push($(this).attr('id'));
console.log(window[rowVar]);
}

Categories