Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object:

 {
    "abc": [{
            "xyz": "INFO 1",
            "pqr": "INFO 2"
        },
        {
            "xyz": "INFO 3",
            "pqr": "INFO 4"
        }
    ]
}

We are looking to extract the following values from the response:

xyz, INFO 1
xyz, INFO 3

Can you assist in retrieving these specific values from the response object?

Answer №1

  1. Transform JSON into a JavaScript object - JSON.parse(jsonString)
  2. Utilize both dot and bracket notations while accessing the values (e.g. JSobject.abc[0].xyz)

const object = {
  "abc": [{
      "xyz": "INFO 1",
      "pqr": "INFO 2"
    },
    {
      "xyz": "INFO 3",
      "pqr": "INFO 4"
    }
  ]
}

console.log(object.abc[0].xyz)

If you are familiar with the structure of JSON data, you can iterate through it to access all the information at once:

const object = {
  "abc": [{
      "xyz": "INFO 1",
      "pqr": "INFO 2"
    },
    {
      "xyz": "INFO 3",
      "pqr": "INFO 4"
    }
  ]
}

object.abc.forEach(o => {
  Object.keys(o).forEach(p => {
    console.log(`${p}, ${o[p]}`)
  })
})

Answer №2

To flatten an array of "xyz" values, you can utilize both JSON.parse and the .map function.

const data = '{ "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" }] }';
const jsonData = JSON.parse(data);
const xyzValues = jsonData.abc.map((item) => item.xyz);
console.log(xyzValues);

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

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Are you ensuring JSON encoding is being done appropriately?

Okay, I am revising my question to ensure clarity on what I aim to achieve. Search.php <?php $getItems = file_get_contents('Items.json'); if(isset($_GET['searchVal'])){ $getItems2 = json_decode($getItems, true); $data2 = ar ...

What is the best way to send a JSON response from a Symfony2 controller?

I am utilizing jQuery to modify my form, which is created using Symfony. The form is displayed within a jQuery dialog and then submitted. Data is successfully stored in the database. However, I am unsure if I need to send some JSON back to jQuery. I am ...

Challenge with Deploying VueJs: Chrome is stuck on the previous version and not refreshing the application

Having issues with deploying my VueJs project, a web application built on the Metronic template and utilizes Vuetify components. When publishing, I use Visual Studio Code with npm run build and upload the contents of the dist folder to my server. Encoun ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

Exploring the Power of Streams in JavaScript

I'm looking to create a stream object that can perform the following actions: // a -------1------2----3 // map -----\------\----\ // b --------2------4----6 const a = new Stream(); const b = a.map(value => value * 2); b.subscribe( ...

Problem with YouTube iFrame API in IE when using JavaScript

Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...

Tips for sending a form without reloading the page in node.js and ejs

<form action="" method="post"> <div class="bottom_wrapper clearfix"> <div class="message_input_wrapper" id="eventForm"> <input class="message_input" name="msg" placeholder="Type your message here..." /> </div ...

Using Jquery to Insert Numbers Inside Brackets to Selection

I am struggling to calculate the sum of numbers in jQuery for selection fields. Currently, my code looks like this. $(function() { $("select").change(function() { updateTotal(); }); updateTotal(); }); function updateTotal() { ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...

Tips for subscribing to an Angular Unit Test:

In the process of writing test cases for a component, I first tackled a basic test case to ensure smooth functionality. Initially, I faced Dependency Injection errors and managed to resolve them. The current challenge I am encountering involves mocking API ...

The JSON sorting functionality seems to be functioning improperly

Here is a sample of my JSON data: [ { "cash": 100, "uid": "LHy2qRGaf3nkWQgU4axO", "name": "test2" }, { "cash": 1000000, "uid": "01wFhCSlnd9vSDY4NIkx", "name": "test" }, { "cash": 500, "uid": "PBOhla0jPwI4PIeNmmPg" ...

Obtain an array from a PHP API and insert it into a table in a Flutter

I need help with handling an API response and iterating through it using a foreach loop... Here is the API code: $user = ""; $ssn = ''; $return["message"] = ""; $return["success"] = false; $post_ref = ""; $error = ""; $array =[]; if ($error == ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Utilize Ant Design TreeSelect to seamlessly integrate API data into its title and value parameters

I am currently working on populating a Tree Select component in ANT Design with data fetched from an API. The response from the API follows this structure: projectData = ProjectData[]; export type ProjectData = { key?: number; projectId: number; ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

Using the onclick attribute as a unique identifier for a button

I am currently facing a challenge with a form that does not have an ID Here is the code snippet in question: <button class="btn btn-primary" onclick="showModal()" type="button">Browse Data</button> Unfortunately, I don't have any contro ...