Building a structured array from nested JSON data using JavaScript

[
    {
        "item": "1",
        "values": [{"name": "A"}]
    },
    {
        "item": "2",
        "values": [{"name": "B"}]
    },
    {
        "item": "3",
        "values": [{"name": "A"}]
    }
]

The desired outcome is to extract ["A", "B"] based on the values in the name field.

How would you approach this task using Javascript? Your insights are appreciated.

Answer №1

At first glance, there seems to be a syntax error in the way your nested array is defined.

"values": ["name": "A"]  // this is not valid javascript

It appears that you may have intended for it to look more like this:

x=[
    {
        "item": "1",
        "values": {"name": "A"}
    },
    {
        "item": "2",
        "values": {"name": "B"}
    },
    {
        "item": "3",
        "values": {"name": "A"}
    }
]

As for your main question - I recommend using underscore JS or the Lodash library, particularly their map functions. Assuming you are working with the object 'x' as defined above and using underscore JS...

.map(x, function(y){return y.values.name})
["A", "B", "A"]

Hopefully this information proves helpful to you.

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

Retrieve all entries in MongoDB using Mongoose where a particular date falls within a specified date range

Consider a scenario where documents contain the fields: startDate: 2021-04-14T22:00:00.000+00:00 endDate: 2021-04-19T22:00:00.000+00:00 You want to retrieve all documents where a specific date (e.g., today) falls within the date range. Is it possible to c ...

What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command: vue create hello-world This generated essential files like HelloWorld.vue, app.vue, and main.js. Next, I followed the documentation on Npm vue-axios to install Axios: npm install --save axios vue-axios In ...

Utilizing the extend method to incorporate an object into a prototype

Every time I attempt to add the object BaseNet to IPv4Address.prototype, I encounter an error: TypeError: Cannot read property 'ipInt' of undefined This error is puzzling. It seems like the getter is being executed when copying the object to ...

What is the best way to transfer a variable to a Promise.all operation?

In the scenario presented, there is an attempt to pass the constant filter into the Promise.all function, but the method of passing it down is proving to be a challenge, resulting in it being undefined in the final line of code. What is the best way to pa ...

Looking for assistance in verifying the schema

I have a collection of local events stored on my disk that follow a specific schema. My next step is to verify these saved results against the JSON schema I have created. Can you advise me on how to accomplish this task? ...

Remove all child subcategories within the selected (sub)category from a cascading dependent dropdown menu selection

I'm currently working on implementing chained dependent dropdown combobox selection. The idea is to have one combobox for the main category, and once the main category is selected, another <select> will appear for choosing a subcategory, and so ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

What could be causing the information from the ajax call to not appear in this popover?

Hovering over a link will trigger a popover with a 1 second delay containing user profile information, loaded using AJAX. $(function() { var timer = null; var xhr = null; $('.user_popup').hover( function(event) { ...

The API is only returning three records, but the backbone collection is not syncing up with

I am working with an API that provides a JSON object of "Groups". Below is the PHP code for this: public function index() { $teams = new Team; $clients = new Client; $organisations = new Organisation; // Get the organisations $org = O ...

Unable to remove the white space appearing below and after a div in HTML

I have been working on creating a website. You can find my JSFiddle here. On my JSFiddle, you might notice a white gap above the black image labeled INSURANCE, and another white gap below it. I've tried various solutions but haven't been able to ...

Tips for effectively managing errors in Next.js getStaticProps

Currently, I am immersed in the development of my inaugural Next.JS application (Next and Strapi). All functionalities are operational, but I am interested in discovering the optimal approach to integrate error handling within getStaticProps. I have exper ...

convert a generic case class to JSON using a writer

I've been attempting to convert this model into Json, but I keep encountering the error message "No apply function found matching unapply parameters." I've tried implementing two different writers to achieve this, but neither seems to be working ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Changing text content of an element with dynamic formatting

When a link is clicked on, I want to dynamically set the text. Here is the current code: <a href="www.somelinkhere.com" onclick="getElementById('setText').innerHTML='text to replace'" target="someIFrame" ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

Exploring the search functionality within Meteor JS

As a newcomer to databases and search functionality, I am exploring how to implement a search feature in my Meteor app. After browsing through atmosphere, I found these 4 options: Mattodem easy search Search Source Elastic search package on Atmosphere (h ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Encountering an issue when trying to run the jQuery $.getJSON() function

I'm currently working on a jQuery Plugin that is designed to retrieve data from a JSON response. For some reason, the success method is not being called. Instead, it goes to the .error() method. Can someone please assist me with this issue? http://w ...

Having trouble with sending a post using ajax? Addressing the bad request issue

Hey there! I'm just dipping my toes into the world of API and could really use some guidance... So, here's the code snippet I've been working on: <!DOCTYPE html> <html> <head> <title></title> <script src ...

Get the shared elements from several arrays with JavaScript

Find the shared value of 12 from the given array For example: If the input is as follows: [ [12, 6],[12, 11, 9, 8, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1] ] The expected Output should be : [12] ...