I am trying to create an object inside a JSON object that will be later populated from FormData:
function toJSONstring(form) {
let object = {`"${form.name}": {}`}; //Property assignment expected.ts(1136)
let formData = new FormData(form);
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if (!Reflect.has(object, key)) {
object[key] = value;
return;
}
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
});
form.reset();
return JSON.stringify(object);
}
What I want to obtain is the following JSON:
{
"network_settings": {
"connection": "wifi",
"type": "dhcp",
"ssid": "Jorj_2.4",
"ip_address": "",
"gateway": "",
"subnet": "",
"dns": ""
}
}
but I get Property assignment expected.ts(1136)
.
If I replace
let object = {`"${form.name}": {}`};
with let object = {};
then I get a normal JSON object:
{
"connection": "wifi",
"type": "dhcp",
"ssid": "Jorj_2.4",
"ip_address": "",
"gateway": "",
"subnet": "",
"dns": ""
}
How can I created the nested object that I want ?
CodePudding user response:
Go back to what you had first:
let object = {};
And after you have populated the object, wrap it using computed property name syntax:
return JSON.stringify({ [form.name]: object });
CodePudding user response:
For dynamic keys in script you have to enclose your expression inside []
const form = {
name: 'network_settings'
}
let obj = {[form.name]: {}};
console.log(obj);