This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
So this is a bit of an unusual situation i am in but what i need to do is access the value of an object based on what index its stored in. The problem is that i need it in my Select component of material ui. So the overview is that i store alginment values of a video . the videos show up in a loop which means the select values are repeated and to know if its for the first video i append the index inside the object like this:
Now in order to set the option i have to access this value here :
Now the problem is in this loop i cant do something like :
halign.halign[index] because obviously that would mean its an array. So long story short how could i do something like :
value={`${halign.halign}${index}`}
So basically the end result for value to evaluate is : halign.halign0
and so on for each index.
NOTE the outer halign is the main useState object.
Remember that for JavaScript objects x['y'] and x.y are interchangeable.
So if you need to compute the key you're looking up, use:
halign['halign' + index]
Or template strings if you prefer.
Note this would be a lot easier if you organized your object with an internal array, so you could just do halign[index].
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.
This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 5 years ago.
I am getting several arrays returned from a GET reponse, which I need to access. Since their names can change based on the request, I have a variable specifing which array to use.
However I always get undefined. See this:
console.log(current); // trips_out_201702
console.log(theResponse.current); // undefined
console.log(theResponse.trips_out_201702); // this works
How can I make theResponse.current work such that it returns what current actually stands for? Why do I get undefined there?
When the property key in an object is a variable you can use the square bracket notation to access that property.
console.log(theResponse[current]);
when acessing with dynamic attribute You should do as
theResponse[current] not theResponse.current
You are trying to get array value using object's way.
You should try this one instant variable['keyName']
Good Luck!
This question already has answers here:
JavaScript: Object Rename Key
(35 answers)
Closed 6 years ago.
Say I have some JSON data like this:
blah = [
{"Species":"setosa","Sepal.Length":5.1,"Sepal.Width":3.5},{"Species":"setosa","Sepal.Length":4.9,"Sepal.Width":3}
]
In my code, I won't necessarily know the key names of the JSON. Therefore, I can grab the keys like this (I do know that all elements of the array are identical in their keys):
mynames = Object.keys(blah[0]); // gives this... ["Species", "Sepal.Length", "Sepal.Width"]
I am able to change the name of the first key called Species here to newthing like this:
JSON.parse(JSON.stringify(blah).split('"Species":').join('"newthing":'));
But if I didn't know it was called 'Species', but knew it was the first element of 'mynames', I thought I could do the same thing like this:
JSON.parse(JSON.stringify(blah).split('mynames[0]:').join('"newthing":'));
or
JSON.parse(JSON.stringify(blah).split('"mynames[0]":').join('"newthing":'));
but both fail. Is there a way of doing this simply?
It seems what you want is
blah[0].newthing = blah[0][mynames[0]];
delete blah[0][mynames[0]];
but knew it was the first element of 'mynames',
Note that the order of keys is not guaranteed, so that might not work in every environment or even for multiple runs.
How do I remove a property from a JavaScript object? explains how the delete keyword can be used to remove properties. You can simply set the new property to the value of the old, then delete the old.
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I have an object with some data inside. The first level of data are 2 arrays (body, cause). Each body and cause array have arrays inside of them (date, year).
totals:[{body:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]},
{cause:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]
}]
What I would like to do is access the body/cause array dynamically based on something the user has changed.
This is how I am accessing them now.
totals[isCause].body[isYear].date[filterNumber]);
My issues is body and date are hard coded in there, and I would like to have access to either body/cause date/year. I can't seem to find what these property names are stored as. I tried to set up a var and do something like this
var bodyCause = "body";
Then I tried to pass it back into my retriever statement.
totals[isCause].bodyCause[isYear].date[filterNumber]);
But that fails. So I'm just trying to figure out what that property name is stored as and if I can dynamically set it when I need to retrieve information.
Your attempt was almost correct. You can easyly use var bodyCause = "body"; and access the content dynamically. Instead of this
totals[isCause].bodyCause[isYear].date[filterNumber]);
you should use this
totals[isCause][bodyCause][isYear].date[filterNumber]);
Should fix your problem.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
Hello I am doing a school assignment my main problem is as follows.
var objectQueue = {
customers:[
{name:"Phil", order:"coffee"},
{name:"Sandy", order:"coffee"},
{name:"Enrique", order:"sandwich"},
{name:"Joe", order:"coffee"},
{name:"Alex", order:"muffin"},
{name:"Zoe", order:"chili"},
{name:"Bahamut", order:"sandwich"},
{name:"Rydia", order:"timbits"}
]
};
I have this object, I need to know how to access each customer's order through a for loop. I can't get the loop to read each person's order. What would be the right way to do this?
This is where I am currently:
objectQueue[x]order
Assuming x is a counter:
objectQueue.customers[x].order
objectQueue has a property named customers, to access a simple property on a Javascript object, you can just use its name:
objectQueue.customers
Then, customers has a array of objects. To access elements in a array, we use its index:
customers[0]
Since the elements in the list are maps/objects, we can access them via properties as well:
customers[0].name
Putting this all together we get:
objectQueue.customers[0].name
Almost everything in Javascript is an object, so it's a little misleading to differentiate between arrays and objects (since arrays ARE objects), but I'm assuming you can dig into those details later if you're interested. In the meantime, this should get you going.
You first need to access the length of the customers and use that as your loop count, from there you can use 'i' your counter to access properties
for (i=0; i<objectQueue.customers.length; i++){
console.log(objectQueue.customers[i]);
console.log(objectQueue.customers[i].name);
console.log(objectQueue.customers[i].order);
}