Instructions on extracting particular elements from a JSON document and converting them into an array

Here is a JSON array that I am working with:

{
  "data": [
    {
      "id": 6,
      "pnome": "dasda",
      "unome": "dad",
      "avatar": 1,
      "email": "d",
      "pass": "password",
      "ponto": 0
    },
    {
      "id": 3,
      "pnome": "Enguias",
      "unome": "Enguias outra vez",
      "avatar": 10,
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c29222b39252d3f0c29222b39252d3f6229222b39252d3f">[email protected]</a>",
      "pass": "enguias",
      "ponto": 0
    },
    {
      "id": 2,
      "pnome": "André",
      "unome": "Marques",
      "avatar": 1,
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4627212a2b273437332306212b272f2a6825292b">[email protected]</a>",
      "pass": "yet1",
      "ponto": 0
    }
  ]
}

I then use Axios to put the JSON data into an array in my code:

axios.get(my_url_api)
.then((res)=>{
const txt = JSON.stringify(res.data.data);
const users = JSON.parse(txt)
})

My goal now is to extract specific attributes like email and pass from the users array. This is how I want it to be displayed:

{
  "data": [
    {
      "email": "d",
      "pass": "password"
    },
    {
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfdad1d8cad6deccffdad1d8cad6decc91dad1d8cad6decc">[email protected]</a>",
      "pass": "enguias"
    },
    {
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f697919a9b9784878393b6919b979f9ad895999b">[email protected]</a>",
      "pass": "yet1"
    }
  ]
}

Answer №1

To simplify the data and remove unnecessary fields, you can utilize the Array.map() function as shown in the example below:

let data = {
"info": [
{
"id": 6,
"name": "John",
"lastname": "Doe",
"avatar": 1,
"email": "john.doe@example.com",
"password": "securepass",
"points": 0
},
{
"id": 3,
"name": "Jane",
"lastname": "Smith",
"avatar": 10,
"email": "jane.smith@example.com",
"password": "janepass",
"points": 0
},
{
"id": 2,
"name": "Alice",
"lastname": "Jones",
"avatar": 1,
"email": "alice.jones@example.com",
"password": "alicepass",
"points": 0
}
]
}

data.info = data.info.map(item => {
    return {
        email: item.email,
        password: item.password
    };
});

console.log(data);

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

What is the best way to create a JSON object for sending it through a POST API in Swift 3?

Below is the format of my key value pair that I need to pass as a parameter: KEY: rest_order VALUE: Enclosed within curly braces rest_order { "address":"liberty", "order_price":"1100", "fname":"rara", "lname":"bbaba", "phone":"1100 ...

The command "electron-rebuild" returns an error message stating, "No Electron application found."

Hey there! I recently installed a native module using npm for Electron (atom shell) and now I'm trying to run electron-rebuild: >>./node_modules/.bin/electron-rebuild I am running this command from the project directory, "~/project_js/React-Re ...

JavaScript can switch the rendering mode from quirks mode to standard mode in Internet Explorer

Is it possible to switch IE from quirks mode to standard mode using JavaScript? I am unable to edit the HTML content header, and adding a new IE=edge meta tag to the head element is not effective (it displays a message stating that the mode has been set ...

How come the information isn't being transferred between components?

Is my method correct if I want to pass the this.prompt() function from TitleBar to Portfolio? This is what my index.html file looks like: var TitleBar = React.createClass({ render: function() { return( <div className="jumbotron"> ...

How can I extract information from an HTML element using its ID in JavaScript?

Can anyone please help me retrieve the date using JavaScript from the following div: <div id="popupDateFieldMin" class="dateField">2017-08-02</div> Below is the code snippet I am currently using: var cal = document.getElementById( 'popu ...

Passing variables in Node.js: passing a variable to a module versus passing a variable to each individual

As I delve into learning node.js, a question arises regarding the distinction between two different scenarios. Suppose I have a variable myvar (such as a database connection or a simple string like "test") that needs to be shared across multiple modules an ...

What is the best way to add a listener for a modification of innerHTML within a <span>?

How can I detect changes inside a particular <span> element in order to attach a handler, but so far have been unsuccessful? Below is the HTML snippet: <span class="pad-truck-number-position"><?php echo $_SESSION['truckId']; ?> ...

What is the best approach to resolving the MongoServerError: E11000 duplicate key error?

Index.Js File: const cookieSession = require("cookie-session"); const express = require("express"); const app = express(); const helmet = require("helmet"); const morgan = require("morgan"); const dotenv = require(&q ...

Managing two different responses in Retrofit can be done effectively by creating separate models for

I went through a tutorial on this website to learn how to use Retrofit2 for POST requests For parsing my POST and GET files, I utilized JSON POJO When the records contain data, I receive a response like the one below { "status": "200", "response": [{ ...

The Google Chart Api utilizes datetime values to enhance data visualization

Hi there! I'm looking to show the datetime in my chart, but I've hit a roadblock. I came across some similar issues on Stack Overflow like this one, but I couldn't quite figure out how to apply the solution to my situation. I believe the pa ...

Performing AJAX requests to interact with another PHP file without navigating away from the current page

I have a question related to an inquiry I made on Stack Overflow about saving events in a database using Fullcalendar. You can view the original post here. At the conclusion of my previous question, I pondered whether using AJAX could be a viable solution ...

Unexpected additional character found in json_encode output

I'm attempting to generate a correctly formatted JSON output using CodeIgniter, but it seems like there is an unnecessary hyphen or dash character in the result displayed below: Below is the snippet of code I'm using to produce the query result: ...

Is it a mongoDB issue or a backend server issue if the Express Server can only GET requests and not POST?

After successfully deploying my first MERN stack project to Heroku, I encountered some issues that were not present during development. Essentially, my web application fetches data from MongoDB and allows users to apply multiple filters for searching. It a ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

Using JSON to transmit image data stored locally

Currently, I am developing a Java web application with Spring MVC. I have a requirement to send an image of a resource using JSON from local storage located at D:\Work\ResourceData\Employee1\Employee1.jpg to a specific URL. Can anyone p ...

Fetching JSON data cross-domain with the help of JavaScript or JQuery

I am currently attempting to retrieve JSON data from this specific url. However, I am encountering difficulties in making it function as intended. The goal is to seamlessly integrate the school's lunch menu utilizing NutriSlice. We are leveraging Ris ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

Validation for an empty string in the value of an input element

Why is my empty string validation not functioning correctly for the value property of an HTMLInputElement after trimming? The issue lies in the code within the storeOnEnter function. My intention is to update the state only when the input field is empty. ...

Is there a way to verify if a user navigated to a specific route or URL using the back button?

What is the best way to implement functionality that triggers when a user returns to a previously visited page in their browsing history? ...

Submit the form with an input value that is located outside of the form

I am facing an issue with a dropdown menu that displays a list of users. When I select a user from the list, a radio button appears with options to Modify user details, Change user Permissions, or Warn User. After choosing an option from the radio buttons ...