A
A
Anton Filippov2015-01-18 21:26:12
JavaScript
Anton Filippov, 2015-01-18 21:26:12

How to name a property in an object?

The essence of the question is that I need to make a cycle that, depending on the id, will display data from the object.
Roughly speaking, there is an array:

var names = [ 
    { id: 1, name: 'Филиппов А. В.' },
    { id: 2, name: 'Иванова А. М.' },
    { id: 3, name: 'Петров В. В.' }
  ];
how can you refer to any of the array objects not by index, but by id ?
If you store everything in an object, a la var names = {1: "Антон", 2: "Маша"}, it doesn’t work, because you can’t refer tonames.1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vyacheslav, 2015-01-18
@vicodin

I see three options:
1. There may be a "sparse" array in js, however, it will not be so convenient to work with it (array traversal will be different, for example).

x = []
x[5] = {...}
x[10] = {...}

And, of course, only integer id.
2. Replace the array with an object.
names = {
1: {...}, 2: {..}
}

You can contact not through names.1, but through names[1].
3. Write an array search function that will traverse the array and search for an object with the desired id in it.
It all depends on your goals

V
vasIvas, 2015-01-18
@vasIvas

names['id'];
In an object, all properties are strings. Therefore, objects cannot be used as keys.
If objects are not specifically given a hash, then there is a high probability that two different objects will be mistaken for one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question