Adding a dynamic amount of values to a JavaScript Object Property

Hi Guys,

I am desperatly trying to add values to an object property. The API I want to communicate with needs all information delivered that way and the amount of values vary.

msg.object = {property: {[var1] : "value1",[var2] : "value2",...}};

I tried some functions like .push() and splice() but they seem not to work for this use case

Thank you so much in advance for any help ! :pray:

Can you give some more info, ie. what is the input and what should become the output ?

I have this object

msg.object = [{property: {[var1] : "value1"}}]

and I want to add more values like with an array I use the .push()-function

msg.object = {property: {[var1] : "value1",[var2] : "value2",...}};

I could write this manually but I have to dynamically add more values because the amount is uncertain

thanks for the reply!

msg.object is setup as an array, but only with a single object. There is no push method for objects, you will need to create new properties:

let obj = [{ property: { key_1: "value1" } }]

let key2 = "key_2"
let key2_value = "value2"

let setObj = obj[0].property   // first get the property key from the single array and create new keys from there. 

setObj[key2] = key2_value

// or as a short hand you could do: 
// obj[0].property[key2] = key2_value

msg.object = obj

return msg;

Output:

[{"property":{"key_1":"value1","key_2":"value2"}}]
1 Like

bakman2 I cannot thank you enough! Your solution works like a charm! To generate an unknown amount of property keys I just had to adjust a little bit of your code to let it act like the push method

msg.object = [{ property: { }}];

for (let i = 0 ; i<5; i++){
msg.object[0].property["key_" +i] = "value_"+i;
}

return msg;

66351358f3618512

I am so glad the node-red community is that awesome :raised_hands:

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.