-1

Supposing we have JSON data who came as :

msg = {
    fieldName: fieldA
};

msg = {
    fieldName: fieldB
};

I can receive multiple of this message, but everytime i have a different field, i want it to add in the 'data' json object, as i can access by using this :

data.fieldA
data.fieldB

By which way can i perform this ?

Nicolas Frbezar
  • 452
  • 1
  • 4
  • 23

1 Answers1

3

To access a property of an object when the name of the property is something your code figures out at runtime:

var propertyName = someCode();
var propertyValue = someObject[propertyName];

To create an object with an object initializer and a computed property name, you can do this in modern (ES2015) JavaScript:

var propertyName = someCode();
var someObject = {
  [propertyName]: someValue
};

Prior to ES2015, you would do this:

var propertyName = someCode();
var someObject = {};
someObject[propertyName] = someValue;
Pointy
  • 389,373
  • 58
  • 564
  • 602