Explore a JSON structure and identify the parent key of a specific key:value pair

I may be new to coding, but I've hit a roadblock and can't seem to find the solution - despite numerous attempts on Google and StackOverflow.

Behold, a JSON object:

const json = {
    "catalog:aardvark": {
        "severity": "minor"
    },
    "catalog:baboon": {
        "severity": "minor",
        "testDependency": "dashboard:echidna"
    },
    "catalog:capybara": {
        "severity": "minor",
        "testDependency": "dashboard:ferret"
    },
    "dashboard:dingo": {
        "severity": "minor"
    },
    "dashboard:echidna": {
        "severity": "minor"
    },
    "dashboard:ferret": {
        "severity": "minor"
    }
}

My challenge is to retrieve the key "catalog:capybara" using either the key "testDependency" or the value "dashboard:ferret". The other inputs are not known for this purpose.

I've attempted various methods without success, and while it seems simple, I'm seeking guidance and assistance. Your help would be greatly appreciated!

PS: Don't let the colons in the keys and values confuse you.

Answer №1

If you want to retrieve the keys of the object and locate the nested object, you can use a function like this:

function findKeyOfNestedObject(object, key, value) {
    return Object.keys(object).find(k => object[k][key] === value);
}

var obj = { "catalog:aardvark": { severity: "minor" }, "catalog:baboon": { severity: "minor", testDependency: "dashboard:echidna" }, "catalog:capybara": { severity: "minor", testDependency: "dashboard:ferret" }, "dashboard:dingo": { severity: "minor" }, "dashboard:echidna": { severity: "minor" }, "dashboard:ferret": { severity: "minor" } };

console.log(findKeyOfNestedObject(obj, 'testDependency', 'dashboard:ferret'));

Answer №2

To convert JSON into an array of keys and values, you can use the following method:

const keyValueArray = Object.keys(json).map((key) => {
    return  {key: key, value: json[key] };
});

Afterwards, you have the option to filter based on specific keys and values:

const filteredArray = keyValueArray.filter((obj) => {
    return obj.key === "catalog:capybara" || obj.value.testDependency === "dashboard:ferret";
});

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

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...

JavaScript tag filtering system: Display only the div elements that contain all the specified classes in an array; otherwise, hide them

Can you provide some guidance on accomplishing this task? I am looking to toggle the visibility of a div based on its classes and an array. If the array contains the term something, then only divs with the class something will be displayed. If the array ...

Converting JSON arrays into Python lists

I am encountering difficulties in parsing a JSON array I created into a Python list. Despite my efforts, I have not been successful in achieving this. Is there a way to convert my JSON array into a Python list? The structure of the json data I want to pa ...

Is it possible to create Interactive Tabs using a Global BehaviorSubject?

Trying to adjust tab visibility based on different sections of the Ionic app, an approach involving a global boolean BehaviorSubject is being utilized. The encapsulated code has been condensed for brevity. In the provider/service globals.ts file, the foll ...

Unable to track user (Mineflayer - Node.js)

Trying to track a player using the mineflayer library in Node.js, but encountering an error within the source code of the library itself. Attempted code: const mineflayer = require('mineflayer'); const { pathfinder, Movements, goals } = require( ...

Methods for sending data from Angular to the server and vice versa

Currently, I have an application that utilizes Express along with Jade templates. I am in the process of developing a new version of the app using Angular and client-side HTML. In order to determine user permissions within my Angular code, I require acces ...

When utilizing "Koa-Rewrite," an AssertionError occurs stating that app.use(rewrite) necessitates a generator function

I am currently working with Koa@1 and koa-rewrite@1 to implement a specific functionality. rewritelogic.js const rewrite = require('koa-rewrite'); function rewriteLogic(){ rewrite('/english/experience/dev1', '/english/experienc ...

Is there anyone available to help me with the task of deserializing my JSON data into C# Objects?

Having some trouble converting JSON to Objects for accessing statistics easily. Currently facing null values in my Dictionary and Dictionary. Any help would be greatly appreciated. Check out this example of my JSON: { "teamStats": { "game2998": { ...

Updating a nested subarray using Node.js with the MongoDB API

I am currently in the process of developing a backend API using Node.js/Express and MongoDB for managing student records. I am facing difficulty with updating a sub-field within the data structure. Below is the code snippet from my Student.js file located ...

Refreshing a data object that is shared among Vue components

I've recently started diving into Vue, and I've found myself responsible for tweaking an existing codebase. There's this data.js file that caught my attention, containing a handful of objects holding city information, like: export default { ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). I've experimented w ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

Setting up flowplayer for multiple div elements: a tutorial

I have a collection of videos and I am trying to set up the player for each div that holds a video. When constructing the divs in my JavaScript code, it looks like this: <div id="player+{{$index}}"></div> // The "player" + index is generat ...

Determine the maximum array size in Javascript

Having trouble setting a limit in my custom lightbox for a gallery <script> var imagenumber = 0; function btnleft(){ load = imagenumber-=1; document.getElementById('lightboxcontent').innerHTML=imagelist[load]; ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Retrieve the value of a specific inner field in a JSON document by targeting a key with jq

I have a JSON file in the format below. To extract the value of the name field based on the id value, when the id value is 99900, it should return DEF. How can I achieve this using jq? { "11213-99900": { "cid": "11213-99900", "name": "DEF", ...

The combination of loading and scrolling JavaScript code is not functioning properly on the website

I created an HTML webpage that includes some JavaScript code to enhance the user experience. However, I encountered an issue when trying to incorporate a load JavaScript function alongside the scroll JavaScript function on my page. The load script is posi ...

`What is the process for accessing page-specific data on Google Analytics using the analyticsreporting tool?`

I'm currently working on extracting specific analytics data using Google's analyticsreporting API v4. Below are the URLs of the pages I am analyzing: https://www.example.com/uiqueId1 https://www.example.com/uiqueId2 https://www.example.com/uiqu ...

Locate the index and value of the item that has the most recent date

Exploring my API design const dataArr = [{ end_date: '2019-12-16' }, { end_date: '2018-12-16' }]; const latestEntry = dataArr.filter( /* Seeking the index of the item with the most recent date */ ); Interested in vanilla JavaScript ...