I was learning Objects in Javascript and i use a users example but i have a question.
let users = [
{
"id": "1",
"name": "John",
"age": 20,
"address": "123 Main Street"
},
{
"id": "2",
"name": "Emma",
"age": 23,
"address": "12 Main Street"
}
]
console.log(users[0].id);
In this code, I used users[0] to access John, but John’s ID is ‘1’, and I used [0] for array indexing style. So, it feels a bit confusing to me. Is this right, or am I coding it incorrectly? Does it follow a commonly recognized style?
I wanted give IDs to users but index numbers with ID numbers looks weird.
3
Answers
You can search your array by id via array.find
To find the object representing John from the users array, you can use the find method. The
find
method iterates over the elements of the users array and returns the first element that satisfies the provided condition. In this case, the conditionuser.name === "John"
checks if the name property of each user object is equal toJohn
.Here’s an example of how you can do it:
When referencing objects such as users with (theoretically) unique ids, best practice usually dictates storing them in a hashmap(ish) key-value structure. In this case you would need to create unique id’s for the users (I recommend something like uuid to ensure unique ids). This object can still be iterated over, but more importantly you can immediately reference objects by their id instead of needing to iterate through an array to find the desired user. This approach applied to your example would look something like this:
Best practice would dictate removing the id parameter to enforce one source of truth for the id, but you could leave it in for the sake of convenience.
Hope this helps!