Created
February 7, 2024 07:47
-
-
Save Kaapiii/a09809e37e5dff3569dd2f0f94171e32 to your computer and use it in GitHub Desktop.
Example of concatenating multiple nested objects with template literals in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
row = { | |
"id": 2, | |
"name": "Erde", | |
"diameterKm": 12756, | |
"gravitation": 9.81, | |
"terrain": "Dschungel, Grasland, Berge, Wüste", | |
"populationCount": 8000000, | |
"prominentPeople": [ | |
{ | |
"name": "Rose Imaginär", | |
"birthYear": 2000, | |
"height": 170, | |
"sex": "female" | |
}, | |
{ | |
"name": "Mike Earthling", | |
"birthYear": 1980, | |
"height": 190, | |
"sex": "female" | |
} | |
] | |
}; | |
let persons data | |
.map(row => { | |
const names = Object.keys(row); | |
const vals = Object.values(row); | |
const prominentPeopleIdx = names.indexOf("prominentPeople"); | |
// Map nested objects | |
if(vals && vals[prominentPeopleIdx]) { | |
vals[prominentPeopleIdx] = vals[prominentPeopleIdx] | |
.map((item) => `${item.name} [${item.birthYear}]`) | |
.join(', '); | |
} | |
return new Function(...names, `return \`${templateRow}\`;`)(...vals); | |
}).join(""); | |
console.log(persons) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment