How can I access a specific JSON object using its key?

Consider the object below:

const ourObject = {
    "payload": {
        "streams": [
            {
                "children": {
                    "2165d20a-6276-468f-a02f-1abd65cad618": {
                        "additionalInformation": {
                            "narrative": {
                                "apple": "A",
                                "banana": "B"
                            },
                            "myInventory": {
                                "fruits": [
                                    {
                                        "name": "apple"
                                    },
                                    {
                                        "name": "banana"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ]
    }
};

We have a task to locate the path of myInventory, however the uuid for children is dynamic. Do you have any suggestions on how we can find the path to myInventory by using it as a key and obtaining the JSON path?

Answer №1

If you're dealing with dynamic elements, utilizing a programmatic key search can be beneficial

const ourObject = {
    "payload": {
        "streams": [
            {
                "children": {
                    "2165d20a-6276-468f-a02f-1abd65cad618": {
                        "additionalInformation": {
                            "narrative": {
                                "apple": "A",
                                "banana": "B"
                            },
                            "myInventory": {
                                "fruits": [
                                    {
                                        "name": "apple"
                                    },
                                    {
                                        "name": "banana"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ]
    }
};

const getPath = (key, o) => {
  if (!o || typeof o !== "object") {
    return "";
  }

  const keys = Object.keys(o);
  for(let i = 0; i < keys.length; i++) {
    if (keys[i] === key ) {
      return key;
    }
    
    const path = getPath(key, o[keys[i]]);
    if (path) {
      return keys[i] + "." + path;
    }
  }
  return "";
};

const getValueForKey = (key, o) => {
  if (!o || typeof o !== "object") {
    return undefined;
  }

  const keys = Object.keys(o);
  for(let i = 0; i < keys.length; i++) {
    if (keys[i] === key ) {
      return o[key];
    }
    
    const value = getValueForKey(key, o[keys[i]]);
    if (value) {
      return value;
    }
  }
  return undefined;
}

console.log(getPath("myInventory", ourObject))
console.log(getValueForKey("myInventory", ourObject))

Answer №2

I'm not entirely certain if I have grasped the question correctly, however,

const uniqueID = '2165d20a-6276-468f-a02f-1abd65cad618';
ourObject.payload.streams[0].children[uniqueID].additionalInformation.myInventory

Answer №3

let keyToChange = Object.keys(myData["payload"]["streams"][0]["children"])[0]; 

console.log(myData["payload"]["streams"][0]["children"][keyToChange]["additionalInfo"]["inventoryAmount"]);

Answer №4

If you need to retrieve the UUID from a payload object efficiently, consider creating a helper function to do so. This approach offers close to O(1) lookup time, especially when dealing with objects that have only one key-value pair.

function extractUUID(payload) {
    let data = payload.streams[0].children;
    let uuid = Object.keys(data)[0];
    return uuid;
}

Usage Example:

const uniqueId = extractUUID(payload);
ourObject.payload.streams[0].children[uniqueId].additionalInformation.myInventory;

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 extent of a variable within a jQuery function?

Similar Question: Understanding Asynchronous Behavior in Ajax Question: Why does my variable "temp" remain as 0 after the AJAX request? function calculate7() { var temp = 0; $.ajax({ type: "POST", ...

Update the default window location when the Browse button is clicked

When a user clicks on the browse button on our webpage to upload a file, I want to change the window location. Currently, when the button is clicked, a window pops up defaulting to "My Documents". However, I would like to change this so that when the user ...

Guide to utilizing the Twitch Emote API

If you're looking to access Twitch emotes through an API, the site provides all the information you need. However, one downside is that they do not offer any examples of requests. For instance, making a call to this URL ( ) will result in a massive ...

Unable to determine why node.js express path is not working

const express = require("express"); const app = express(); app.use(express.static("public")); var dirname = __dirname; app.get("/:lang/:app",function(req,res){ console.log(req.params.lang + " " + req.params.app); ...

Iterate through a JSON array and categorize items based on their key values

Upon decoding the JSON, I received the following Array: $json = Array ( [name] => Array ( [0] => Peter [1] => David ) [dep] => Array ( [0] => accounts [1] => sales ) [date] => Array ( [0] => 10/27/2015 [1] => 09/25/2015 ) ); Is ...

Troubleshooting: jQuery AJAX Post - Issue with Greater than conditional not functioning as expected

Having an issue with a conditional in my code. Everything is functioning properly except for this specific line. <if condition="$show['member']"> <script type="text/javascript" > $(function() { $("#submitbutton$post[postid]").click(f ...

Decoding JSON data from OpenWeatherMap using Swift

Although I have successfully established the connection, I am encountering difficulty extracting the description from the weather Array. The issue lies in the fact that it is a Dictionary nested within an Array. {"weather": [{"id":801,& ...

What is the process for creating a hover linear wipe transition using CSS/JS?

It's worth noting that I can't simply stack one image on top of the other because I'll be dealing with transparent images as well. preview of linear wipe ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

What is the best way to convert the information from a <SelectInput /> component or similar components into another language?

Within my React admin v3 application, When retrieving data from the servers for my entity, I receive a unique identifier called a slug. This slug is a special key that needs to be translated on the client side. Here is an example of my <CallMeBackCre ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

When an element in vue.js is selected using focus, it does not trigger re

One of my tasks involves tracking the last selected input in order to append a specific string or variable to it later on. created: function () { document.addEventListener('focusin', this.focusChanged); } focusChanged(event) { if (event ...

Is there a way to stop a <script> element's code from executing again if I modify one of its DOM parent elements?

Let's simplify the scenario at hand. On a webpage, there is a particular section of HTML structured like this: <div id="wrap-this"> <script> $(document).ready(function() { alert('Blah.'); }); ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Test an express + sequelize server using chai-http ping command

Currently facing challenges while setting up tests using Express and Sequelize. The testing framework being used is Mocha + Chai. Initially, only a ping test is being attempted. The code snippet from server.js: const express = require('express&apos ...

Fetching data in a post request seems to be causing an issue with FormData image being

I've implemented a profile picture file upload system with the following HTML: <form enctype="multipart/form-data" id="imageUpload" > <img id="profileImage" src="./images/avatar.png& ...

Ways to eliminate a specific array from another array using JavaScript

0: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 1: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 2: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_am ...

Adding multiple elements to an array in React can be achieved by using helper methods like spread

I'm currently working with two classes - one that holds the array and another that holds the array props. Here is an overview of these classes: //PARENT CLASS: constructor() { super() this.state = { items: [] } this.addItem = thi ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...