Ways to extract particular keys from a JSON array?

I am receiving an array of JSON objects in my response.

{"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":51,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"log4j-2022.01.25","_type":"log4j_type","_id":"x5AWkX4BkHwsqoJA8hbA","_score":1.0,"_source":{"@timestamp":"2022-01-25T11:55:07.221Z","commands":"wc,trim,uniq,sort","message":"2022-01-25 17:25:06 wc,trim,uniq,sort sharon","@version":"1","host":"sharon","time":"2022-01-25 17:25:06","username":"sharon","path":"/home/sharon/Log/Logging.log"}},{"_index":"log4j-2022.01.25","_type":"log4j_type","_id":"yJAXkX4BkHwsqoJAAhZi","_score":1.0,"_source":{"@timestamp":"2022-01-25T11:55:11.224Z","commands":"wc,sort,trim,uniq","message":"2022-01-25 17:25:10 wc,sort,trim,uniq sharon","@version":"1","host":"sharon","time":"2022-01-25 17:25:10","username":"sharon","path":"/home/sharon/Log/Logging.log"}},...]}}

I am looking to extract the 'username' and 'commands' fields from each JSON object. I used axios to fetch the data. How can I achieve this?

const query = {
    query: {
      match_all: {},
    },
    _source: ["time"],
  };
  axios
    .get("http://localhost:9200/log4j-2022.01.25/_search", query)
    .then((res) => {
      console.log(res.data);
    });

Thank you in advance

Answer №1

Your JSON data appears to contain an unexpected [. If this is the case, the following code snippet can help you extract the username and commands properties:

let extractedData = jsonData.hits.hits.map(
    ({_source: {username, commands}}) => ({username, commands})
);

With the provided example data, the extracted information will be stored in extractedData as follows:

[
  { "username": "sharon", "commands": "wc,trim,uniq,sort" },
  { "username": "sharon", "commands": "wc,sort,trim,uniq" }
]

Answer №2

const { result } = response.data.result

const updatedResult = result.map((item) => ({ actions: item._source.actions, user: item._source.user }))

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

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Can you upload a file using the MaterialUI Upload Button in React and then send it to Firestorage?

Hi everyone! I recently implemented MaterialUI's Upload Button in my project, which you can find here: https://material-ui.com/components/buttons/ Below you will see the code snippet where I have integrated this button and now I am trying to upload a ...

Expand the div width to the specified measurement horizontally

Is there a way to horizontally collapse a div (container) to a specific width that I can adjust, effectively hiding its content? The collapse effect should move towards the left. <div id="container"> <button type="button" id="myButton"> ...

TableData - hyperlink cell

I am currently using Datatable to present data and loading a table through an AJAX call to a JSON object. One of the columns needs to display as a text with a link that opens a modal window. "columns": [ { 'data': 'BATCH'}, { ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

Sending data from an Angular 2 application to a Spring MVC Rest API using HTTP POST method

I'm encountering an issue while attempting to perform an angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam. Despite my efforts of searching for a solution, I have not been successful in binding it to my object. I even ...

Steps to resolve the TypeError: RelatedManager object does not support iteration

I am working with two models, Meeting and Meetingmemeber, to store information about a meeting and the invited participants. Here is how I have set up the serializer: class MeetingSerializer(serializers.ModelSerializer): location = MeetingLocationSer ...

Expanding the size of a div using the Bootstrap grid system

I need to customize the width of the date column on my inbox page so that it displays inline without breaking the word. Even when I use white-space: nowrap, the overflow hides it due to the fixed width. I want the name and date classes to be displayed in ...

Search for elements within the database by using the recursive feature of M

I am working on a search query to retrieve 'n' number of videos from a collection. The user has primary, secondary, and tertiary language preferences (Tamil(P), Hindi(S), English(T)). My goal is to first search for videos in the primary language, ...

Ensuring the accuracy of a single field within a form containing multiple fields is made possible through the utilization of

I am facing an issue with my emailValidation method. Even though I want it to run when this.$refs.editUserForm.validate('email') returns true, it always seems to return false, especially when a valid email like <a href="/cdn-cgi/l/email-protec ...

Exploring Node.js: Uncovering the Secrets of Checking Dependency Versions

How can I dynamically retrieve the version of an external dependency in JavaScript without manually specifying it? ...

Steps to generate an error in the 'response' function of a $httpProvider interceptor

I am currently working on creating a custom HTTP interceptor in Angular and I am looking to generate an error from the response of the $httpProvider interceptor. According to the provided documentation: response: Interceptors are triggered by the http re ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

Attaching Picture From Array To Vue

Is it possible for me to request assistance? I'm wondering how to bind an image to a vue component or more simply, how do you render an image from an array in vue? Allow me to share my code with you and explain in detail how I have approached this. W ...

Error message in Angular about undefined JavaScript function

Struggling to make my Angular 17 project functional with Bootstrap (5) and the datePicker feature. Despite following tutorials, I keep encountering a "ReferenceError: datePicker is not defined" error during the app build process. Here are the steps I&apos ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...

Changing the CSS property of a single table cell's innerHTML

I have a question that may seem silly, but I'm going to ask it anyway. Currently, I am iterating through a list of strings that follow the format "1H 20MIN" and adding them to table cells using the innerHTML property like so: for (i = 0; i < list ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...