How can I create JSON object javascript dynamically without concatenating strings? I have the following JSON structure for employees, but I don’t know how many rows or columns there will be:
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
Assuming I receive each row in an onGeneratedRow method, how can I push each column (like firstName and lastName) into the object dynamically?
I’ve worked with dynamically building JSON structures a lot, and using arrays and object literals is a really clean way to handle this. Here’s how you can do it:
var viewData = {
employees: []
};
function onGeneratedRow(columnsResult) {
var employee = {}; // Create a new object for each employee
columnsResult.forEach(function(column) {
var columnName = column.metadata.colName; // Get the column name
employee[columnName] = column.value; // Assign value dynamically
});
viewData.employees.push(employee); // Push the employee object to the array
}
This way, you can create JSON objects in JavaScript without manually concatenating strings, which makes the code cleaner and easier to maintain.
Another technique I’ve used a lot, especially when you want to embrace a more functional programming style, is leveraging reduce()
. It’s neat and concise:
var viewData = {
employees: []
};
function onGeneratedRow(columnsResult) {
var employee = columnsResult.reduce((acc, column) => {
acc[column.metadata.colName] = column.value; // Dynamically create properties
return acc; // Return the accumulator
}, {});
viewData.employees.push(employee); // Add the employee object to the employees array
}
Using reduce()
here lets you create JSON objects in JavaScript efficiently, as it handles the object-building in a straightforward, functional way.
For those who want a simpler and more explicit style, I’ve found using a for...of
loop works great. It’s pretty clear to read:
var viewData = {
employees: []
};
function onGeneratedRow(columnsResult) {
var employee = {}; // Create a new employee object
for (const column of columnsResult) {
employee[column.metadata.colName] = column.value; // Assign values dynamically
}
viewData.employees.push(employee); // Add the employee object to the array
}
This approach is very readable and makes it easy to create JSON objects in JavaScript dynamically as you receive new data.