Look for and choose various fields from a lengthy JSON object

I am working with a JSON object that contains a large list of offerValue objects.

{
    "Code": 0,
    "response": "SUCCESS",
    "offerValue": [
        {
            "id": "111",
            "name": "ABC",
            "flag": "V" 
        },
        {
            "id": "222",
            "name": "DEF",
            "flag": "A"
        },
        {
            "id": "333",
            "name": "XYZ",
            "flag": "G"
        },
        {
            "id": "444",
            "name": "FER",
            "flag": "H"
        }
    ],
    "sessionId": null
}

With the use of ES6, my goal is to search for an object where name is "ABC", and if found, extract the corresponding flag value ("V" in this example).

Answer №1

Hey Chris, big thanks for the shoutout...

Here's the solution to the query -

const jsonData = {
    "Code": 0,
    "response": "SUCCESS",
    "offerValue": [
        {
            "id": "111",
            "name": "ABC",
            "flag": "V" 
        },
        {
            "id": "222",
            "name": "DEF",
            "flag": "A"
        },
        {
            "id": "333",
            "name": "XYZ",
            "flag": "G"
        },
        {
            "id": "444",
            "name": "FER",
            "flag": "H"
        }
    ],
    "sessionId": null
}

const offersList = jsonData.offerValue;

const resultObj = offersList.find(({name}) => name === 'ABC');

if (resultObj){
console.log(resultObj.flag)
//additional logic goes here

}

Answer №2

One way to streamline the array is by condensing it into a lone flag value. For instance:

const selectedFlag = obj.offerValue.reduce((accumulator, currentOffer) => {
if (currentOffer.name === 'ABC') return currentOffer.flag;
return accumulator;
}, null);

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

tag of data in jquery

Here is how my setup looks: <div onclick="EditCalendarEvent('@_schedulerEvent.SchedulerID','@_schedulerEvent.SchedulerItemID', event)" class="ScheduleEvent_Draggable ScheduleEvent" data-schedulerID="@_schedul ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

Encountering a node-gyp error during the deployment of a Rails 6 application with a Vue app on Heroku

I'm running into an issue when trying to deploy my Rails 6 app with Vue on Heroku. The error I'm getting is as follows: [4/4] Building fresh packages... error /tmp/build_c242c7d78580af478535f5a344ff701e/node_modules/fibers: Command failed. ...

WCF JSON Post functions correctly in Visual Studio but encounters issues in IIS 7.5

I'm experiencing a strange issue with my WCF Service in IIS. GET requests are functioning properly, but when it comes to POST requests, they only work when I run the service from Visual Studio. When I try to use IIS, I receive an Error 400 Bad Request ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Guide on iteratively creating and appending data to a JSON file

My testing scenario involves calling the addEachEmployeeDetailsToJSONFile method multiple times with different employee details each time. The desired outcome is to generate a JSON file named mapping.json structured as follows: EXPECTED mapping.json Stru ...

Leveraging the power of mapState and mapMutations within a namespaced module

I'm having trouble accessing mutations and states after dividing my Vuex store into three modules. I've attempted various syntaxes, but none seem to be working for me. MapStates: This is how I have set up the mapStates, with 'vendor' a ...

Step by step guide to creating individual counter sections

I have set up a counter section where the numbers go from 0 to a specific value. However, currently all three counters start counting simultaneously. Is there a way for the first counter to count up first, then once it's done, move on to the second c ...

Could anyone help me locate the section in the MUI documentation that explains the correct syntax for the commented code lines I am working on?

Before proceeding, please note that the ThemeProvider with theme={theme} has already been provided. Now, I will share two distinct sets of code files. These files contain sections commented out because they are not functioning as intended when implementing ...

What is the process for extracting information from one table based on a column's data in another table?

Let's consider two tables: Table 1 id | email 1 | email1 2 | email2 Table 2 userid | username 2 | user1 3 | user2 Now, with the help of sails.js associations, here is what I aim to achieve: I have a username = user1. What I need to a ...

Accessing JSON data in AngularJS from Node.js as the backend and SQL database

I am currently working on a project that involves setting up a node.js server in the backend and using AngularJS in the frontend. In order to fetch information from an SQL database, I have implemented a simple GET request as shown below: req.execute(&apos ...

Is it possible to use jQuery to refresh only a section of the page and modify the URL at the same time?

There is a page (http://myflashpics.com/picture/p9e0) that displays user information along with a small thumbnail on the side. Currently, when clicking on the image, it redirects to a different page and the sidebar reloads as well. I am curious if it' ...

Attempting to parse a file using JSON.parse

I'm currently in the process of downloading a file and attempting to utilize JSON.parse. The result should be { dateTime: "2012-04-07T17:15:00.000-05:00", value: "1065.91" }. Can someone verify if I am passing the correct object through JSON.parse and ...

Discover the key steps to extracting codes within a string in React or Javascript

I am currently developing an application that could potentially receive a string from the backend server. The string might look something like this: If you were to fold a piece of paper in half 50 times, its width would be three-quarters of the distance fr ...

At what point is it necessary to generate a new vertex array object when sketching numerous objects?

I'm embarking on a game development project using WebGL. Currently, I have three textures in my arsenal- one for letters used in the font, another for character sprites, and a tilemap texture for the world. With these large textures at hand, I find m ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

Having trouble retrieving the innerHTML of a span tag in a JavaScript function

I'm currently working on creating an email message that will have pre-filled text from an asp:Literal when a user clicks a link. The HTML code for this is structured like this: <tr> <td> <img src="../../images/Question.gif" ...

Loading JSON data from a file in an AngularJS service

Looking to retrieve JSON data from a file named driverStandings.json, which can be found in the structure from the provided image. I am utilizing a service API to fetch this information by using the code displayed below (refer to image). After compiling, ...