Retrieving a specific value from a JSON object using the find method in JavaScript

Having difficulty extracting the value of jersey_num from the JSON data below.

const json = [{
    $: {
        Type: "first_name"
    },
    _: "Evan"
}, {
    $: {
        Type: "last_name"
    },
    _: "Ferguson"
}, {
    $: {
        Type: "birth_date"
    },
    _: "2004-10-19"
}, {
    $: {
        Type: "weight"
    },
    _: "Unknown"
}, {
    $: {
        Type: "height"
    },
    _: "Unknown"
}, {
    $: {
        Type: "jersey_num"
    },
    _: "28"
}, {
    $: {
        Type: "real_position"
    },
    _: "Striker"
}, {
    $: {
        Type: "real_position_side"
    },
    _: "Centre"
}, {
    $: {
        Type: "join_date"
    },
    _: "2021-08-23"
}, {
    $: {
        Type: "country"
    },
    _: "Republic of Ireland"
}]

Attempted to retrieve using the code below, but got back an undefined result.

const jersey = Object.entries(json).find(([, e]) => Object.values(e).includes('jersey_num'))
console.log(jersey)

I suspect there might be something amiss in my code. Any guidance on how to properly extract the jersey_num value would be greatly appreciated.

EDIT

  1. Rectified the JSON object to correct format
  2. The desired value for extraction is '28' corresponding to Type: "jersey_num"

Answer №1

Instead of manually grabbing the entries from the json array, you can directly use array methods like .find() to search for a specific object based on a condition. In this case, we are looking for an object with the $.Type value equal to jersey_num.

const json = [{ "_": "Evan", "$": { "Type": "first_name" } }, { "_": "Ferguson", "$": { "Type": "last_name" } }, { "_": "2004-10-19", "$": { "Type": "birth_date" } }, { "_": "Unknown", "$": { "Type": "weight" } }, { "_": "Unknown", "$": { "Type": "height" } }, { "_": "28", "$": { "Type": "jersey_num" } }, { "_": "Striker", "$": { "Type": "real_position" } }, { "_": "Centre", "$": { "Type": "real_position_side" } }, { "_": "2021-08-23", "$": { "Type": "join_date" } }, { "_": "Republic of Ireland", "$": { "Type": "country" } }];

const obj = json.find(obj => obj.$.Type === "jersey_num");
console.log(obj?._);

This code snippet demonstrates how you can safely access a property using optional chaining (?.). Using optional chaining helps prevent errors in cases where the desired object is not found within the array.

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

Top approach for accessing data through a Factory function in Angular

Seeking guidance on the most effective method for fetching data from a local JSON file and managing the response. The plethora of options found on Stack Overflow has left me with conflicting thoughts, as different approaches yield similar results without c ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...

Is it true that all events in JavaScript go through capturing and bubbling phases?

My current project involves binding one eventListener to an <audio> element for the play event and another eventListener to its parent element for the same event. I've observed that the callback for the child element always gets executed, while ...

Creating a 3D element using JSON data in combination of Three.js and React.js

Let me explain the situation as best as I can. I am currently working on a React.js application and learning as I go. I am in the process of incorporating a 3D element into my page, specifically a sofa, that users can interact with using their mouse to mov ...

Guide to updating user input on the screen when a click event occurs using Javascript and HTML

I've been working on writing HTML and JavaScript code that enables user input to change based on which button the user clicks. The idea is that the user enters find/replace values, and when they hit the replace button, the text they initially entered ...

What is the reason that Object.keys(window) or for(k in window) does not include the Math object?

As I work on creating a JavaScript editor autocomplete feature, my goal is to showcase all available top-level elements. So far, I've experimented with: Object.keys(window) as well as for (k in window) However, it seems like neither method include ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...

What is the rationale behind not passing $scope to a service in AngularJS, and is it considered bad practice?

Is it advisable not to pass $scope to a service for certain reasons? I understand that services are intended to be reusable singletons, and passing a (potentially) large object to the service could lead to maintenance issues. However, assuming there is so ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Configuring git npm dependencies to aid in debugging purposes

This is my first time trying to debug a library in my application and I'm not entirely sure how to go about it. I initially installed the library with npm install @react-pdf/renderer, but debugging was proving difficult. Then, I found a useful answer ...

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

parsing in Swift can fail when trying to decode key-value pairs

Here are the models I am working with: struct City: Decodable { let famous: Flags let name: Name } struct Name: Decodable { var common , official : String var nativeName: [String:NativeName] enum CodingKeys: String, CodingKey { ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

Adding a new element in between existing elements of an array using PHP

My PHP code is generating a dynamic JSON array that looks like this: {"key":"user_email","relation":"=","value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3a32...</a>"}, {"key":"user_email","relation":"=","value": ...

javascript - The window.onload event is not firing

I am currently working on developing a tool that will allow users to export a PDF file. There are two scenarios to consider: The first scenario involves a straightforward process where the user clicks the export button, and a new blank window opens imm ...

Exploring the potential of Oracle Openscript in combination with Javascript using AngularJS,

I have encountered an issue while using Openscript on a form page with a clickable "save" button implemented as a div. Manually clicking the button triggers a javascript event that saves any changes made on the page. However, when I run the script, the but ...