I have a situation where I need to search a database, but the format of the newer and larger database is different from the old one. I am looking for a way to convert the new format back to the original format, but I am unsure of how to do this. Here's what I'm dealing with.
In the original array of objects:
let people = [{"name": "John", "country": "England", "hair": "brown"},
{"name": "Jenny", "country": "Scotland", "hair": "black"}]
The new array is structured like this:
let newPeople = [{
"John": {"country": "England", "hair": "brown"},
"Jenny": {"country": "Scotland", "hair": "black"}
}]
Previously, I had a function to search the people
array that worked in a certain way:
function getCountry(name) {
for (let i = 0; i < people.length; i++) {
if (name === people[i].name) {
return people[i].country;
}
}
}
This function would perfectly return Jenny's country by using:
getCountry("Jenny") // returns "Scotland"
Now, in the "newPeople" array, to retrieve Jenny's country, I need to use:
newPeople[0].Jenny["country"]
This method is quite complex, as each person is nested within newPeople[0] instead of being accessible directly. Additionally, I cannot utilize the same for-loop or match the searched term using "name" due to the absence of the "name" attribute in the new array.
Is there a way to easily transform the new array into the original format? If possible, I would prefer to revert the entire database to the previous structure rather than adapting to the new format.