S
S
Stone-Studio2016-05-31 09:52:57
JavaScript
Stone-Studio, 2016-05-31 09:52:57

How to refer to an object, knowing its name as a string?

I have an object name which is a string value. There is an object with the name of that same string value. For example, I have the string value "one". (id = "one") There is an object one (one = {two: "three"}). You need to contact via id. id.two doesn't work, of course. How to refer to an object, knowing its name in a string?

Anticipating the question, why, I will answer. Each element id has its own object. The structure is the same, the data is different. IDs are written in HTML and when clicking on a link, we get its id and must refer to the object property of this element.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Misty Hedgehog, 2016-05-31
@paramtamtam

If I understand your question correctly, then you should know that the elements of an object can be accessed as elements of an array. Example:

var source = {
  'one': {
    id: 1,
    name: 'Name1',
  },
  'two': {
    id: 2,
    name: 'Name2',
  }};

console.log(source['one']['name']);
console.log(source['two']['name']);

Will return:
Name1
Name2

D
Denis Ineshin, 2016-05-31
@IonDen

Complicate the structure a little, then everything will be simple:

var storage = {
    id1: {one: 1, two: 2},
    id2: {one: 1, two: 2}
}

Now we forget about the dot notation and pass the names of the properties as strings:
If you still really want to keep such id-objects at the root, then you can contact through window:
var one = window["id1"]["one"];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question