This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Dynamic property names for loop of object Javascript
In success of javascript function I receveing data and it look like this:
data.lvl1
data.lvl2
data.lvl3
...
let say I have only 3 elements in data and I would like to loop for each of them and rise alert for every level:
for(a = 1; a<= 3; a++)
{
alert(data.lvl + a);
//I would like to read lvl1, lvl2, lvl3
}
This approach is obviously wrong.
Please explain how to reach lvl1, lvl2 in loop when lvl number is based on increasing a.
If you want to access a property name using a string, then use square bracket notation.
foo.bar === foo['bar']
Such:
alert(data['lvl' + a]);
But it would be better to restructure your data so that you had something like:
data = { lvl: [1,2,3] }
instead of
data = { lvl1: 1, lvl2: 2, lvl3: 3 }
Related
This question already has answers here:
Iterate over defined elements of a JS array
(7 answers)
Closed 3 years ago.
I'm new to coding and this situation poses quite a problem for me. I'm working with reactjs and inside a function I have props like this:
const{a,b,c,d,e,f,g,h} = props
So 'props' is an object, 'c' is an array, inside 'c' are 100 objects ranging from 'idx' 0 to 99, all these objects have an identical property call 'x', 'x' value is boolean 'true' or 'false'. I want to know the best way to loop through all these 100 objects so it will return 'true' or 'false'
Basically, c is like this:
let c = [{x:true},{x:true},{x:false}];
I only know so far as
console.log ('show value', props.c[idx])
to show key and value inside this object but cannot take the key I want by props.c[idx].x . I think I was wrong some where. Please help
Bonus: I want to know this so for every 'true', a button TRUE appear and vice versa, it's kinda like this
{!x (<button> False </button>)}
It's a bit hard to interpret your question. But wouldn't this is what you're looking for (I use array of 3 elements, but it should work for 100 of them):
let c = [{x:true},{x:true},{x:false}];
console.log(c.map(c=>c.x));
Let's assume that your data structure for props looks like this.
var props= {c : [{x:false},{x:true},{x:false},{x:true},{x:false},{x:true},{x:true}]}
Then your accessing method is indeed correct. Working snippet below!
var props= {c : [{x:false},{x:true},{x:false},{x:true},{x:false},{x:true},{x:true}]}
console.log("props.c[idx] value is : ",props.c[0])
console.log("props.c[idx].x value is : ",props.c[0].x)
console.log("=================================================");
//loop through all
for(idx in props.c){
console.log("Loop ",idx," : ",props.c[idx].x);
}
This question already has answers here:
JavaScript set object key by variable
(8 answers)
Closed 3 years ago.
I am trying to create an array with the following data as example. I want to set the named index dynamically based on the user selected value. But when I set the index to a variable, the declared variable name is considered a string in the array and set as the array index name.
var country = userInputFromUi;
var cities = [a,b,c,d];
array.push({
country:cities
})
Expected result
userInputFromUi:[a,b,c,d]
actual result
country:[a,b,c,d]
Not sure if I am understanding something wrong here.
Use computed property names like so:
array.push({ [country]: cities });
This question already has answers here:
Is there any way to use a numeric type as an object key?
(11 answers)
Closed 4 years ago.
i have a JSON object (sent from php) and I want to convert the IDs to a numeric key using JS. So currently it looks something like that:
let foo = {"66":"test","65":"footest"};
And now I want it to look like this:
let foo = {66:"test",65:"footest"};
Object keys do not need to be numerical to be accessed - as noted in the comments - they are strings regardless.- Below, I am console logging the "66" property using the brackets notation - foo[66]
let foo = {"66":"test","65":"footest"};
console.log(foo[66]); // gives "test"
// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
foo[i] = "test" + i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}
This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I need to update a value in my JSON.
My JSON result looks like this:
results = {"ROWCOUNT":50,"COLUMNS":["PERSONID","NAME"],"DATA":{"PERSONID":["42","43","44"], "NAME":["JOE","TOM","JANE"]}
resultData = results.DATA
In the below code I am looping over the result set and attempting to update a value at a position. I believe it is failing because I am not using dynamic variables correctly.
var columnName = "NAME";
for(i=0; i < results.ROWCOUNT; i++ ){
resultData.columnName[i] = "foo" // failing here due to "columnName" being dynamic.
}
Figured it out.. You have to use array syntax
resultData[columName][i]