It's well known, that 'array of objects' format of data storage is well suitable for data persisting. I'd be extremely grateful if a JavaScript guru helps me with finding the answer to how do I read this HTML-table with vanilla JavaScript and transport data from it into the following array of objects.
I have produced tons of code, mostly comparing two arrays of objects. Unfortunately, I didn't come even closer to a solution.
The table to scrape data from:
<table>
<tbody>
<tr>
<td colspan="3">Canada</td>
</tr>
<tr>
<td>Toronto</td>
<td>Montreal</td>
<td>Vancouver</td>
</tr>
<tr>
<td colspan="3">USA</td>
</tr>
<tr>
<td>New York</td>
<td>Chicago</td>
<td>Boston</td>
</tr>
<tr>
<td>Washington</td>
<td>Detroit</td>
<td>Los Angeles</td>
</tr>
</tbody>
</table>
Expected outcome to be like so:
[
{"country":"Canada","city":"Toronto"},
{"country":"Canada","city":"Montreal"},
{"country":"Canada","city":"Vancouver"},
{"country":"USA","city":"New York"},
{"country":"USA","city":"Chicago"},
{"country":"USA","city":"Boston"},
{"country":"USA","city":"Washington"},
{"country":"USA","city":"Detroit"},
{"country":"USA","city":"Los Angeles"}
]
The code is valid, unlike the approach:
let theResult = [];
arrayOfCountriesAndCitiesObjects.forEach((item, iIndex) => {
arrayOfCitiesObjects.forEach((elem, eIndex) => {
if(item.city !== elem.city && item.iIndex < elem.eIndex) theResult.push(copy(elem, item));
});
});
function copy(firstObj) {
for (let i = 1; i < arguments.length; i++) {
let arg = arguments[i];
for (let key in arg) {
firstObj[key] = arg[key];
}
}
return firstObj;
}
forloop solution can be much faster on a small input table, though.