Differences in search functionality between arrays of objects and objects of objects

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.

Answer №1

To loop through the data, you can utilize Object.keys(newPeople), which will give you an array of keys for "newPeople". In this scenario, the resulting array would be ["John", "Jenny"].

However, if your objective is to access a single object within an array that always contains just one object (similar to the example you provided), you can simply do:

function getCountry(name) {
  return newPeople[0][name].country;
}

If your array may not always have all names within a single object, then you will need to iterate through it as follows:

function getCountry(name) {
    for (let i = 0; i < people.length; i++) {
        if (name in people[i]) {
            return people[i][name].country;
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

State is failing to display on the user interface, while an element has been included in the

I have encountered an issue with my react application. I am passing an array of objects to render in the UI, but when I add a new element to it using useState, the element is added successfully but does not render in the UI. Below is the JSX code for refer ...

Steps to correctly reset an XMLHttpRequest object

I'm currently working on a project where I send AJAX requests, receive responses, and replace text based on those responses. However, it seems like I may be missing a fundamental concept in my approach. request.onreadystatechange = () => { if (r ...

Removing redundant elements from an array

Seeking assistance with removing duplicate elements from an array using my own method. Here's the code I have tried: x=[2,1,3,5,3,5] for i in range(0,len(x)): for j in range(0,len(x)): if (x[i]==x[j+1]): del x[j+1] for k in range(0 ...

The component fails to update after a change in state

I'm currently working on a project that involves fetching videos from YouTube and displaying them on the browser. I have successfully retrieved the videos and updated the state property (confirmed using console log). However, I am facing an issue whe ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Utilize alternating colors from the Material UI palette to enhance the appearance of

Can someone help me understand how to utilize the different color variants in Material UI? For instance, the theme primary color has various options like 100, 200, 300, 400, 500, and so on. How can I access these colors from within my component? I attempt ...

Seamless infinite background scrolling on the canvas without any disruptions

In my HTML5/JS project, I have implemented infinite background scrolling using multiple canvases. The challenge I am facing is that while the animation is smooth after rendering, there is a quick hiccup when transitioning to the next frame due to the need ...

Unlocking the content hidden between tokens

Seeking guidance on retrieving values from tokens. I have developed a program that divides sentences using the token "[ ]". Is it feasible to extract the character within these brackets? For instance, how can I extract the number 5000 from the in ...

Innovative grid system powered by AngularJS

I've structured my code into separate layers: 1. A factory that handles all of my $http requests and returns a promise. 2. A controller that manages the promise using a then function to assign it to a $scope variable for display on a gridview. Now, I ...

TPL operating on a List that is stocked with merchandise

I am facing an issue with the following code snippet: {[displayDate(dateRelease);]} Every model available in the store comes with a "dateRelease" property. I want to retrieve that date and format it using my displayDate() function before displaying it. ...

Show the parent at 100% of its size with a fixed position

Can anyone provide assistance? I am attempting to set a maximum height for an image while keeping its width automatic. The issue is that these rules are not being applied because the parent element has a fixed position. View the DEMO here #myDiv { po ...

Steps for adjusting the port number in a Vue.js CLI project

Is it possible to modify the Port number within a Vue-CLI project in order for it to operate on a different port other than 8080? ...

How to create a new tab for a linked page on a Blogger website

Is there a way to make a link in Blogger open in a new tab? I have a basic free template with limited pages. I want to be able to ensure that when a specific text link is clicked, it opens the corresponding link in a new tab. For example, if a visitor c ...

Creating an array of drawables in Android Studio: A step-by-step guide

I've been encountering an issue while using android studio for creating an app that involves an Array of drawables, which allows traversal using forward and backward buttons. The majority of the code has been completed, however, I am facing an error w ...

Is a key implicitly created when referring to an array?

Could someone please clarify why this code prints 'true' without any errors or warnings? If I remove the reference on the array in the code, it will instead print 'false' and give a notice about the index not existing. What is the dif ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

Creating dynamic visuals using SVG with <symbol> tag

I am attempting to generate an SVG element using JavaScript and then append it to the DOM. The SVG element makes reference to a symbol. I have found success using the insertAdjacentHTML method, but I am struggling to achieve the same result with the append ...

Combining a 3D numpy array with a pandas Dataframe and a 1D vector

I am currently working with a dataset that is stored as a numpy array with the shape of (1536 x 16 x 48). This data represents EEG readings collected by sensors at a rate of 256Hz. To break down these dimensions: There are 1536 values which equate to 6 se ...

What could be causing issues with my setup for submitting forms in Django and using jQuery AJAX?

Although I have encountered questions like this numerous times before, I am struggling to make my AJAX form function correctly using jQuery on the client side and Django on the server side. Despite researching extensively, I have not come across a step-by- ...