Joline
Joline

Reputation: 25

Node-Red: Create a message with variable keys/identifiers

There is a message like that:

[
    {
        "source_id": 1,
        "alias": "myalias1",
    },
    {
        "source_id": 2,
        "alias": "myalias2",
    }
]

and I want to change it into a message like that:

[
    {
        "myalias1": 1,
    },
    {
        "myalias2": 2,
    }
]

Trying to do this, I use this function:

var result = [];
var str = "";

for(var i = 0; i < msg.payload.length; i++)
{  
    var alias = msg.payload[i].alias;
    var src = msg.payload[i].source_id;
    result.push({ alias : src });
}

msg.options = result;
return msg;

But this gives a message:

[
    {
        "alias": 1,
    },
    {
        "alias": 2,
    }
]

In the line "result.push({ alias : src });" everything what I tryed to use as an identifier (var alias) will be interpreted as string, even there are no apostrophes. How can I use the value of a variable as an identifier in a message?

Upvotes: 0

Views: 1274

Answers (1)

hardillb
hardillb

Reputation: 59648

You need to use the square bracket notation to add a key to an object from a variable.

var result = [];
var str = "";
for(var i = 0; i < msg.payload.length; i++)
{  
    var alias = msg.payload[i].alias;
    var src = msg.payload[i].source_id;
    var entry = {}
    entry[alias] = src
    result.push(entry);
}

msg.options = result;
return msg;

Upvotes: 1

Related Questions