Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object.

Here is the JSON data I am working with:

[
  {
    "some_key1": [
      {"key": "value1"},
      {"key": "value2"},
      {"key": "value3"}
    ]
  },
  {
    "some_key2": [
      {"key": "value4"},
      {"key": "value5"},
      {"key": "value6"}
    ]
  },
  {
    "default_val": [
      {"key": "value7"},
      {"key": "value8"},
      {"key": "value9"}
    ]
  }
]

The structure of this JSON may vary, but it always consists of inner objects.

Below is the implementation of a function that will retrieve the array of values based on the provided key:

interface InnerObject {
    key: string;
}

const fetchValues = (key = "default_val"): InnerObject[] => {
    /* actual code goes here */
}

Expected output example:

> fetchValues("some_key2");
[{"key": "value4"},{"key": "value5"},{"key": "value6"}]
> fetchValues();
[{"key": "value7"},{"key": "value8"},{"key": "value9"}]

Looking forward to any elegant solutions!

Answer №1

Similar approach like Nick's, but utilizing find to directly retrieve the object:

const data = [
  {
    "some_key1": [
      {"key": "value1"},
      {"key": "value2"},
      {"key": "value3"}
    ]
  },
  {
    "some_key2": [
      {"key": "value4"},
      {"key": "value5"},
      {"key": "value6"}
    ]
  },
  {
    "default_val": [
      {"key": "value7"},
      {"key": "value8"},
      {"key": "value9"}
    ]
  }
];

const getValues = (key = 'default_val') => data.find(o => Object.keys(o)[0] == key);

console.log(getValues('some_key2'));
console.log(getValues());

Answer №2

It would be beneficial to reconsider the current data structure for more efficient searching. Perhaps transforming it into a more suitable format before conducting searches could yield better results.

A potential alternative structure may look like this:

const makeSearcher = (input, obj = Object .assign (...input)) => (key) =>
  obj [key] || obj .default_val

const input = [{some_key1: [{key: "value1"}, {key: "value2"}, {key: "value3"}]}, {some_key2: [{key: "value4"}, {key: "value5"}, {key: "value6"}]}, {default_val: [{key: "value7"}, {key: "value8"}, {key: "value9"}]}]

const search = makeSearcher (input)

console .log (search ('some_key2'))
console .log (search ())

This approach assumes only one object corresponds to each key. In cases where multiple objects share the same key, considering Nick's solution might be wise.

Although the provided O (1) search function is efficient, any logical solution is not expected to surpass O (n). Therefore, performance is unlikely to pose a significant obstacle in this scenario.

Answer №3

Here is a solution:

function fetchValues(key = "default_val"): InnerObject[] {
  return data.find(item => item[key])[key];
};

Answer №4

To filter specific values from an array of objects based on a key, you can utilize the Array.filter method and specify the desired key as a parameter:

const data = [
  {
    "some_key1": [
      {"key": "value1"},
      {"key": "value2"},
      {"key": "value3"}
    ]
  },
  {
    "some_key2": [
      {"key": "value4"},
      {"key": "value5"},
      {"key": "value6"}
    ]
  },
  {
    "default_val": [
      {"key": "value7"},
      {"key": "value8"},
      {"key": "value9"}
    ]
  }
];

const getValues = (key = 'default_val') => data.filter(o => Object.keys(o)[0] == key);

console.log(getValues('some_key2'));
console.log(getValues());

In cases where multiple values match the search key, this code will return all matches. For more efficient retrieval when expecting only one result, consider using Array.find explained in alternative solutions.

Answer №5

Check out this versatile approach using object-scan

One of the key benefits is its ability to easily target deeper keys and multiple keys at once.

// Sample code snippet to demonstrate object scanning with object-scan

const myData = [{ some_key1: [{ key: 'value1' }, { key: 'value2' }, { key: 'value3' }] }, { some_key2: [{ key: 'value4' }, { key: 'value5' }, { key: 'value6' }] }, { default_val: [{ key: 'value7' }, { key: 'value8' }, { key: 'value9' }] }];

const find = (data, key) => objectScan([key], { reverse: false, rtn: 'value' })(data)

console.log(find(myData, '[*].some_key2[*]'));
// => [ { key: 'value4' }, { key: 'value5' }, { key: 'value6' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c232e26292f38613f2f2d220c7d7f6274627c">[email protected]</a>"></script>

Disclaimer: The creator of object-scan has written this post.

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 seems to be ignoring CSS styles when displaying list items in the ng-repeat loop

After coming across a tutorial on creating round circles connected by a line in CSS, I decided to implement it myself. Interestingly, everything worked perfectly fine when I tested it with static HTML. However, when I tried to make it dynamic using Angular ...

Modifications to the selected input do not impact the current state of the model

Declare 3 select inputs with hierarchical data to be chosen: <select data-ng-model="current.manufacturer" data-ng-options="c.name for c in manufactures"></select> <select data-ng-model="current.mark" data-ng-options="c.name for c in current ...

Sending connected functions an object from Qt's cpp interface is currently not possible

I am trying to retrieve a JSON file from a URL and store it in a QtNetworkReply *reply. I then want to send the reply to a connected function where I can convert it into a QbyteArray to parse my JSON response. However, when I enter my connected function, ...

The curious case of Node.JS: The mysterious behaviour of await not waiting

I am currently utilizing a lambda function within AWS to perform certain tasks, and it is essential for the function to retrieve some data from the AWS SSM resource in order to carry out its operations effectively. However, I am encountering difficulties i ...

Storing ng-change event for a checkbox in AngularJS in a valid manner

I have a requirement where I need to handle multiple input checkboxes. The goal is to store the changed checkbox events in an array and then save them when the user submits the changes. <td><input type="checkbox" class="switch" ng-model="each_val ...

Ways to smoothly navigate to a specific element across various browsers with jQuery animation

This particular piece of code is causing some cross-browser compatibility issues: jQuery('body').animate({scrollTop: target.offset().top}, 300); Interestingly, it works perfectly in Firefox but not in Chrome. A different version of the same co ...

What could be causing the error "Err: user.validPassword is not a function" to occur

I am in the process of developing a node.js app and I have implemented Passport js. After referring to the Passport-local documentation on their official website, I decided to utilize the local passport-strategy. However, I encountered an error stating tha ...

Using both PHP and jQuery to add a class upon changing the URL

I am struggling to implement sorting functionality on my webpage, as the active class is not being added to the selected sorting option... Check out my code snippet below: <ul class="nav nav-tabs"> <li class="menusel active" name="hlavni" on ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

On the first load, Next.js retrieves a token from an API and saves it for later use

Currently working on an application with next.js, the challenge lies in retrieving a guest token from an API and storing it in a cookie for use throughout the entire application. My goal is to have this token set in the cookie before any page is loaded. H ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

Discovering hyperlinks without using HTML code

As a beginner in the world of coding, I decided to take on a simple first project: scraping the URLs linked from the map on this webpage. However, I've hit a roadblock trying to figure out how the map directs users to each state's website since t ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Enrich TypeScript objects by incorporating additional properties beyond the ones already present

If I have an expression and want to add extra properties without repeating existing ones, how can I achieve that? For instance, if the expression is a variable, it's simple to include additional fields (like adding field e): const x = { a: 1 }; cons ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

Steps for Deactivating Past Dates on JQuery Datepicker1. Open your

I've been working on a custom JQuery Calendar for selecting appointments, with the requirement to disable dates prior to the current date and highlight available dates in an orange color (#f48024). Unfortunately, my attempt using minDate hasn't b ...

Is it possible to interchangeably use a text file and a json file? If so, what is the best way to do this in Python?

Question: Can JSON and txt files be easily interchangeable in Python? Additional Information: While researching the difference between JSON and XML formats on the internet, I came across this, as well as this discussion on Stack Overflow: this link. Howev ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

Guide to modify target blank setting in Internet Explorer 8

<a href="brochure.pdf" target="_blank" >Click here to download the brochure as a PDF file</a> Unfortunately, using 'target blank' to open links in a new tab is not supported in Internet Explorer 8. Are there any alternative solutio ...