V
V
vizaville2015-04-19 15:22:28
JavaScript
vizaville, 2015-04-19 15:22:28

How to set object name from variable?

How to set object name from variable?
For example
{ countBase: { type: 'base_t' } }
, how to make it so that the attribute name can be set from a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Petrov, 2015-04-19
@Petroveg

Yes, perhaps not directly :) According to the specification , the property name can be the value of a string or a character.
There are several options for working (I don’t know where the age comes from :).
The old fashioned way (or for dictionaries)

var countName = [
    'Петя',
    'Вася'
  ];

for (var i = 0, data = []; i < countName.length; ++i) {
  data.push({});
  data[data.length - 1][countName[i]] = {
    age: 10
  };
}

The same balls, only on the side
for (var i = 0, data = []; i < countName.length; ++i) {
  data.push(set(countName[i], 10));
}

function set (name, value) {
  var object = {};

  object[name] = {
    age: value
  };
  return object;
}

Or using Object.defineProperty() (you can vary property parameters)
for (var i = 0, data = []; i < countName.length; ++i) {
  data.push(set(countName[i], 10));
}

function set (name, value) {
  var object = {};

  Object.defineProperty(object, name, {
    value: {
      age: value
    }
  });
  return object;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question