skip to Main Content

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


  1. You can search your array by id via array.find

    console.log(users.find(function(a) { return a.id == 1}));
    
    Login or Signup to reply.
  2. 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 condition user.name === "John" checks if the name property of each user object is equal to John.

    Here’s an example of how you can do it:

    let users = [
        {
            "id": "1",
            "name": "John",
            "age": 20,
            "address": "123 Main Street"
        },
    
        {
            "id": "2",
            "name": "Emma",
            "age": 23,
            "address": "12 Main Street"
        }
    ]
    let john = users.find(user => user.name === "John");
    console.log(john.id); 
    console.log(john.age);
    console.log(john.address);
    Login or Signup to reply.
  3. 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:

    let users = {
      "1": {
          "id": "1",
          "name": "John",
          "age": 20,
          "address": "123 Main Street"
      },
    
      "2": {
          "id": "2",
          "name": "Emma",
          "age": 23,
          "address": "12 Main Street"
      }
    }
    
    console.log(users['1'].name);
    

    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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search