Extract information from a JSON Object using a specific pathway

Let's consider a scenario where we have a JSON Object structured as follows:

var data = {
    "name": "abcd",
    "age": 21,
    "address": {
        "streetAddress": "88 8nd Street",
        "city": "New York"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "111 111-1111"
        },
        {
            "type": "fax",
            "number": "222 222-2222"
        }
    ]
}

Now, the task is to extract information from this JSON object using a path specified as a string. For example:

var age = 'data/age'; // accessing age
var cityPath = 'data/address/city'; // accessing city
var faxNumber = 'data/phoneNumber/1/number'; // accessing fax number

The current method involves splitting the path by / and then referencing it like data.age or data.address.city. This method does not work efficiently for arrays within the JSON object.

Are there any alternative and more efficient approaches in JavaScript to tackle this issue?

Answer №1

This is a simple way to retrieve data from JSON without the need for complex paths:

var data = {
    "name": "abcd",
    "age": 21,
    "address": {
        "streetAddress": "88 8nd Street",
        "city": "New York"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "111 111-1111"
        },
        {
            "type": "fax",
            "number": "222 222-2222"
        }
    ]
}

var age = data.age;
var cityPath = data.address.city;
var faxNumber = data.phoneNumber[0].number; // remember arrays start with index 0

console.log({age, cityPath, faxNumber})

If you find yourself needing to use paths in your JSON data, consider using lodash's get method https://lodash.com/docs#get

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

AngularJs stops the link from being clicked more than once

I am utilizing AngularJS for specific features in my system, not to build a single-page application. I am struggling to determine why Angular is preventing the page from refreshing after navigating there or how to disable/find a workaround. Here is an exa ...

extracting data from a JSON file containing numerous JSON objects

I encountered an issue with my JSON file that was generated as a response from running multiple parallel curl statements (GET requests to a service). When attempting to parse the JSON file using Python, I faced an error due to multiple JSON objects being ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

Using Angular to create HTTP routes in conjunction with Node.js

My current challenge involves trying to access a .json file that contains my portfolio. I have set up my backend using express js, and am attempting to retrieve the data using angular in the following manner: $http.get("data/items.json") .success(function ...

The Telegram Login component is not displaying properly within a React single-page application

I am currently working on a React frontend application that was created using create-react-app, with Django running at the backend. We have separate development and production environments, each with its own domain. My goal now is to integrate a widget int ...

Issue: Sumoselect plugin unable to function properly when interacting with dynamically generated select dropdown

I recently started using the sumoselect plugin, which can be found at . In my project, I have implemented two select dropdowns. The first one is directly added to the HTML page, while the second one is generated dynamically using jQuery. Unfortunately, t ...

Executing RegisterStartupScript repeatedly in C#

Greetings to all, Here is a snippet from my code: start code protected void Button1_Click(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script>loadAdditionalInfoDialog(info1)< ...

Is it possible to create an AngularJS and jQuery Calendar Directive that activates by clicking on a Bootstrap glyphicon?

I have successfully created a directive for my calendar using AngularJS and jQuery. The datepicker pops up when the user selects the input box. Now, I am attempting to allow the user to click on Bootstrap's 'glyphicon glyphicon-calendar' to ...

Is it possible to retry NTLM Authentication failure in Sails.JS?

Currently, my NodeJS application is built on Sails.JS and uses ntlm-express for NTLM authentication. Everything works smoothly when the authentication is successful. However, when it fails (such as when a Firefox user enters incorrect credentials), ntlm-ex ...

Strange yellow border appears when key is pressed in Quasar's QLayout

While working on a project with the quasar framework and electron.js, I encountered a strange bug where pressing a key causes the application frame to display a persistent yellow border. This border cannot be overridden, removed, or selected using devtools ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Gulp encountered an issue - TypeError: When attempting to call the 'match' method, it was found to be undefined

Currently, I'm attempting to utilize Gulp alongside BrowserSync for a website that is being hosted on MAMP and proxied through localhost:8888. Unfortunately, upon running gulp, I encounter the following error: [17:38:48] Starting 'browser-sync& ...

Modify the hover color of <TextField /> within the createMuiTheme() function

Is there a way to change the borderColor on hover for the outlined <TextField /> Component within the createMuiTheme()? I have managed to do it easily for the underlined <Input /> export default createMuiTheme({ MuiInput: { &apo ...

Refresh my website's specific table automatically whenever the database is updated. Alternatively, reload the table every 2 seconds to ensure the latest values from the database are displayed

How can I update table values in real-time when the database in phpMyAdmin is updated? I have implemented some code that successfully updates the data on my webpage, but the issue is that the entire page reloads every 2 seconds. Is there a way to only ...

The JsonParser functionality on android is malfunctioning

Looking at my JSONObject on this link, I realized that my JSON parser is not functioning correctly. It seems like the issue lies within the parser itself as there are no null errors coming from my list. Here is a snippet of my parser: class exTourPars ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...