Sirhc
19 December 2023 04:20
1
Hello
I need to set multiple objects in a payload before sending.
I need it to look like:
payload
pool_api_code: ABC
temperature_scaler: 1
I have tried:
msg.payload = {"pool_api_code": "ABC" + "temperature_scaler": 1 }
but that does not work. Can anyone help me with the correct syntax?
I need to set multiple objects in a payload before sending.
Do you mean that you need to set multiple properties ?
There are multiple ways - the concept is:
{ property: value, property: value, ... }
some examples
msg.payload = { pool_api_code:"ABC", temperature_scaler: 1 }
return msg
or
const payload = {}
payload.pool_api_code = "ABC"
payload.temperature_scaler = 1
msg.payload = payload
return msg
or (this will create the property names automatically)
const pool_api_code = "ABC"
const temperature_scaler = 1
msg.payload = {pool_api_code, temperature_scaler}
2 Likes
Colin
19 December 2023 10:48
3
I didn't know you could do that. Thanks for the education. Did that appear in a recent version of nodejs or have I just been asleep at the wheel?
2 Likes
I do this often, I think it's been around for some time, but can't find any reference to when it was a thing
EDIT
Found - The computed property names feature was introduced in ECMAScript 2015(ES6)
Object.assign/create
may be a better choice if it is uncertain if the object changes afterwards.
But this can also be very useful if you want to combine multiple objects into a single object, by using the spread operator:
const a = {a:true}
const b = {b:[],c:false}
const obj = {...a, ...b} // {"a":true,"b":[],"c":false}
Same can be done with arrays as well (also to get unique values with [...new Set(array)]
, but we are getting distracted ;))
system
Closed
17 February 2024 11:50
6
This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.