Let's say I have an object looking like this obj = {"column1": ["value1", "value"], "column2": ["value3", "value4"]}
. Am I able to convert that object to a list of objects looking like this using vanilla javascript: arr = [{"column1": "value1", "column2": "value3"}, {"column1": "value2", "column2": "value4"}]
.
I'm trying to create a table in html. Using obj in itself will work to create a table, but when introducing things like pagination, filtering and sorting, it seems kind of difficult to have an object like that.
function generateTableHead(table, obj, test2) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key in obj) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
function generateCells(table, obj) {
var length = (<string[]>Object.values(obj)[0]).length;
var tbody = document.createElement("tbody");
table.appendChild(tbody);
for (let i = 0; i < length; i ) {
let row = tbody.insertRow();
for (let key in obj) {
if (obj[key].length <= i) {
break;
}
let cell = row.insertCell();
let text = document.createTextNode(obj[key][i]);
cell.append(text);
}
}
}
CodePudding user response:
Assuming every column is the same length, then you can create an empty object, go through each column add the column/value pair with the value's index as the key in the new object, then use Object.values()
to convert the object into an array. Like this:
obj = {"column1": ["value1", "value"], "column2": ["value3", "value4"]};
let arr = {};
for (const col in obj) {
obj[col].forEach((el, i) => {
if (!arr[i]) arr[i] = {};
arr[i][col] = el;
});
}
arr = Object.values(arr);
console.log(arr)
CodePudding user response:
Yes, it is possible to convert the object to a list of objects using vanilla JavaScript. One way to achieve this would be to use the Object.entries() method to get an array of key-value pairs from the original object, then use a for loop to iterate through the array and create a new object for each key-value pair, where the key is the property name and the value is the property value. Here's an example of how this could be done:
let arr = [];
let obj = {"column1": ["value1", "value2"], "column2": ["value3", "value4"]};
let entries = Object.entries(obj);
for (let i = 0; i < entries[0][1].length; i ) {
let newObj = {};
for (let [key, value] of entries) {
newObj[key] = value[i];
}
arr.push(newObj);
}
This code will convert the original object into an array of objects where each object has the same keys as the original object, but only one value for each key. This array can be easily manipulated and use as you need it.