1

I'm trying to dynamically add JSON to an array:

let output = [];
let input = [{"Packages":"111","Weight":"2","Id":"row-0"},
             {"Number__c":"123","Packages":"123","Id":"row-1"}]
let tmp;
let f = 5;
let s = f.toString();
tmp = {f : input};
output.push(tmp);

console.log(JSON.stringify(output));

I want to have the key "f" in this case be represented as 5 in the output but it comes through as "f"

console:

[{"f":[
{"Packages":"111","Weight":"2","Id":"row-0"},
{"Number__c":"123","Packages":"123","Id":"row-1"}]
}]

gotta be possible, right?

1 Answer 1

2

You can use JSON construction to get the desired result as:

let input = [{"Packages":"111","Weight":"2","Id":"row-0"},
         {"Number__c":"123","Packages":"123","Id":"row-1"}];
let f = 5;
let output = [];
var obj = {};
obj[f] = input;
output.push(obj);

This can be solved with other different techniques as well, refer this question: Add dynamic key, value pairs to JavaScript array or hash table

3
  • Thanks, but I need 5 to be dynamic. I am getting it from a variable
    – mackmama
    Mar 27, 2021 at 22:49
  • 1
    Updated the answer with some psuedo code
    – Raul
    Mar 27, 2021 at 23:29
  • Awesome! That did it. Thanks guys!
    – mackmama
    Mar 28, 2021 at 0:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .