1

i have dynamic data thats coming into my application, the data structure is the same but the name of the property name being reported on changes. I am trying to write a function that would accept the value of the property variable input to a function and assign it as a variable name.

In the code below, for the measurements variable I want the variable name 'tag' to be the value of the 'tagName' input for the fucntion. Appreciate any help i can get with this! Thankyou!

function iotcjson(device, tagName, value) {

  var data = {
    device: { deviceId: device },
    measurements: { tag: value }
  }

  return data
}

Considering value of tagName is "temperature"

Actual result:

{"device":{"deviceId":"device1"},"measurements"{"tag":11.2}}

Desired Result:

{"device":{"deviceId":"device1"},"measurements"{"temperature":11.2}} 
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    Possible duplicate of [Dynamic object property names?](https://stackoverflow.com/questions/1798446/dynamic-object-property-names) and [Creating object with dynamic keys](https://stackoverflow.com/questions/19837916) – adiga May 10 '19 at 19:33

1 Answers1

2

You could take a computed property name for the wanted result.

For device, you could take the later property name directly of deviceId and insert this variable as short hand property.

function iotcjson(deviceId, tagName, value) {
   var data = {
       device: { deviceId },
       measurements: { [tagName]: value }
    };
    return data;
}

console.log(iotcjson('device1', 'temperature', 11.2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392