I think I've read all the previous responses to any similar questions without finding an answer.
I am trying to build a JSON structure that looks like this (but much bigger :));
[{"APC": {
"Description": "",
"Data": "001,044,1064",
"Units": "",
"AbbrvUnits": ""
}
}, {"DATE": {
"Description": "",
"Data": 1487858497000,
"Units": "Date",
"AbbrvUnits": ""
}}]
But the closest I can get is this data structure;
[{
"DataItem": "APC",
"DataVal": {
"Description": "",
"Data": "001,044,1064",
"Units": "",
"AbbrvUnits": ""
}
}, {
"DataItem": "DATE",
"DataVal": {
"Description": "",
"Data": 1487858497000,
"Units": "Date",
"AbbrvUnits": ""}}]
with this javascript (node-red):
DataVal = {
'Description' : "",
'Data' : DataValue,
'Units' : UnitsStr,
'AbbrvUnits' : ""
};
outputJSON.push({'DataItem' : label, DataVal});
If I try:
outputJSON.push({label : DataVal});
I simply get "label" in the resulting structure instead of its value. Is it possible to get Javascript to expand the variable 'label' and put its value in? There are some examples of declaring 2 data variables to do something like this but they all effectively hard code the 'label' value in the declaration. However, there are a lot of the 'label' items so I really do not want to hard code it. It will also make this generic for other similar data I have.
Is this a limitation of Javascript or am I missing something?
This:
outputJSON.push({'DataItem' : label, DataVal});
Should look like this:
var obj = {};
obj[label] = DataVal;
outputJSON.push(obj);
Objects are key-value
pairs, so, in your original code, you're passing an object that has a key of DataItem
and a value of the value of label
, and, because of the way JavaScript now parses object declarations it parses:
{DataVal} as {"DataVal":DataVal}
EDIT
This last part (about how {DataVal}
is parsed) is as of ECMAScript 2015 (Shorthand Property Names) and more can be read about it under Object Initializer on MDN