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

Fetching client-side data in a Functional Component using Next JS: The proper approach

I have a functional component that includes a form with existing data that needs to be populated and updated by the user. Within this component, I am using a custom hook for form handling. Here is an example: const [about, aboutInput] = useInput({ t ...

How to retrieve data obtained from parsing readline and fs in node.js beyond the scope of the callback function

This specific question diverges from the one mentioned with an existing answer. It pertains to a snippet of code taken from node.js documentation involving the use of fs and readfile, with a focus on detecting an end-of-file flag, which appears to be the r ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

Is it possible to use async in the onChange handler of a React event?

Can async be used to pause execution until a function completes within an onChange event? Here is an example: const onChange = async (e) => { console.log(current[e.target.name]); await setCurrent({ ...current, [e.target.name]: e.targe ...

Is there a way to make all Bootstrap column heights equal using only jQuery?

I am currently working on matching the heights of two columns without using an existing library like match-height.js. In this specific case, I have a row with 2 columns where the first column contains a centered black square and the second column contains ...

What are the steps to incorporate ThreeJS' FontLoader in a Vue project?

I am encountering an issue while attempting to generate text in three.js using a font loader. Despite my efforts, I am facing difficulties in loading the font file. What could be causing this problem? const loader = new FontLoader(); loader.load( ' ...

The updateItem function in the JSGrid controller was not called

Currently, I am working on a project involving js-grid. However, I have encountered an issue where the updateitem function of the controller is not being invoked when attempting to update a column field. Additionally, the field resets to its old value wi ...

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

Troubleshooting MySQL through PHP for errors

I've developed a comment posting system where users can write and submit comments using PHP, MySQL, jQuery, AJAX, and JSON. However, I encountered an issue with JSON insertion while debugging the system with Firebug. The error message displayed was: ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

How can we address the tagging directive problem of binding tags as an array of JSON objects and ensuring that tagging functions properly with the ng-keypress event?

Check out this plnkr example. I'm having trouble binding my tags list with ng-model. I want to bind the tags as an array of objects on a function call using ng-keypress, and then post it to a json file in a specific format. Here is what I am looking f ...

Having trouble accessing the `then` property of undefined while utilizing Promise.all()?

An issue has occurred where the property 'then' of undefined cannot be read: getAll(id).then((resp) => {...} ... export function getAll(id){ all([getOne(id), getTwo(id)]); } ... export all(){ return Promise.all([...arg]) } I' ...

Changing the background color of required inputs that are empty using jQuery

I need help customizing the background color of required input fields that are left empty when a user submits a form. Some of the fields are optional, but I want only the required ones to be highlighted in red. Specifically, the required fields have been ...

Apply Jquery to add emphasis to every item on the list

Can someone help me with this assignment? I need to create a jQuery function that italicizes all list elements on the page when triggered by the client. Here is my current approach: $(document).ready(function() { $("li").click(function() { ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...

Managing numerical data in a CSV file using JavaScript and Google Visualization Table

A JavaScript snippet provided below will load a CSV file named numericalData.csv, which contains headers in the first row and numerical values starting from the second row. The data is then displayed using a Google Visualization Table. I am looking to con ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...