Variable into JSON object path?

Greetings. Is there an easy way to insert a variable as part of a new payload path object? For example :

1 var dev = payload.data.message.dev_id
2 // Extract Device ID last 4 digits to use for identifying variables
3 var eui = dev.substr(12,4)
4 // Declare variables, including the decoding ‘payload_raw’ to HEX:
5 var raw = payload.data.message.payload_raw
6 var buf = new Buffer(raw, ‘base64’)
7 var hex = buf.toString(‘hex’)
8 // Now, extract how many bytes in the payload and add to a ‘payload_cnt’ variable:
9 var cnt = hex.length
10 // Add these new objects to the new payload variables :
11 payload.data.message.device_id = eui
12 payload.data.message.payload_hex = hex
13 payload.data.message.payload_cnt = cnt

The above works so far, but I would like in line 12 and 13 for ‘device_id’ / eui to be included. For example, if eui = ‘be76’ then path for line 12 would read payload.data.message.payload_hex_be76 or similar. Line 13 output would read payload.data.message.payload_cnt_be76 or similar.

Thanks, j

Hi @Jose_Cruz!

We can solve this with some JavaScript magic :sparkles:

In JavaScript, you can also reference the object using the array syntax.

Let’s say you had something like this:

{
   payload: {
       data: "Something"
  }

}

You can access data like this:

payload.data

or like this:

payload['data']

Being that to be true, you can add new variables like this:

var key = 'payload_hex_be76'
payload[key] = '0AFF'
console.log(payload.payload_hex_be76) // prints 0AFF
1 Like

Awesome! Let me try work/learn someof this magic then! Thank you for your prompt reply :smiley: ! :red_circle:

2 Likes

It took me a cpl of days with its nights, some :beers: and :fireworks: , but I finally got it following your lead @anaptfox. This did the trick :

var dev = payload.data.message.dev_id
var eui = dev.substr(12,4)
var pth = “payload_hex_”
payload.data.message[pth + eui] = hex

payload now is assigned with the dynamic ‘eui’ variable (dev_id) of the device, in this case ‘be76’ :

  • “payload_hex_be76”:“1f0200”

Thank you again for the :mage: tip!

2 Likes