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);
}
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:
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].
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I am having a hard time trying to accessing any elements in my object.
Find below my code that accesses the object from the localStorage and prints it out on the browser console:
var test = localStorage.getItem('transactionData');
console.log(test);
The above code yields:
[{Amount":"15,000","payersNumber":"070505788","waitersName":"Agnes"}]
When I try to access the element waitersName as seen in the code below:
console.log(">> " +test.waitersName);
It yields:
>> undefined
How do I access the various elements in my object?
test is an array with an object in it, you'll need to access the array item first with test[0] and that will return the object, which will then allow you to access its properties.
The data you retrieve from localstorage is a stringified version of the Javascript array. You first have to parse it using
var array = JSON.parse(test);
Then get your elements from the parsed array.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I have some line of code that I don't fully understand. I am looking through objects in an api and was wondering what is the purpose of the [i] in d2.follows[i].user.display_name if the code is:
$.getJSON(followerURL, function(d2){
for(var i=0; i<d2.follows.length; i++){
var displayName = d2.follows[i].user.display_name;
following.push(displayName);
I'm searching through object to find the number of followers a channel has. is Here is an image of the object I would greatly appreciate an explanation of this block of code.
As per you JSON Object, it fetches the follows element, which is an array.
Then it takes each element in the follows array and get the user object and its attribute display_name.
Obj -> follows -> user -> display_name
This lists down all the display names of the users.
d2.follows should b an array of objects
To get the displayName from each objects, we should iterate through the array. The [i] helps to iterate through the array elements.
The [i] in d2.follows[i].user.display_name uses the i value from the for loop to set displayName. More or less it goes through the array one by one and reads a value.
I'm unfamiliar with the Twitch API, but if the follows array consists of people who are following someone, then follows.length will give you the amount of followers.
getJSON function return you this object here d2 main object returned from function. for(var i=0; i<d2.follows.length; i++) loop for get each item in the follows list. var displayName = d2.follows[i].user.display_name; here d2.follows[i] is a each item and each item have a user property which is a object and have a display_name property here you set last one property to displayName variable then you call following.push(displayName); following suspect is a array which is a have a push method
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.