Exploring JSON data through key-value pairs

When faced with a de-serialized JSON object that has an arbitrary structure and mixed value types...

var data = {
  'a':'A1',
  'b':'B1',
  'c': [
    {'a':'A2', 'b':true}, 
    {'a':'A3', 'b': [1, 2, 3]}
  ]};

The goal is to extract an array of values that correspond to a specific key.

> my_func(data, 'a')
['A1', 'A2', 'A3']

> my_func(data, 'b')
['B1', true, [1, 2, 3]]

The current implementation returns the correct result, but there may be room for improvement in terms of efficiency or readability.

my_func = function(o,s,a){
    var a = a || [];
    if(o == null){
        return a;
    }
    if(s in o){
        a.push(o[s]);
    }
    for(e in o){
        if(typeof(o[e]) == "object"){
            a.concat(my_func(o[e], s, a))
        }
    }
    return a;
}

Open to suggestions for enhancements.

Answer №1

function exploreObject(obj, callback, parent) {
  for (key in obj){
    callback.apply(this,[key,obj[key],parent]);      
    if (obj[key] instanceof Object && !(obj[key] instanceof Array)) {
      exploreObject(obj[i],callback, key);
    }
  }
}

function findPropertyByRecursion(obj, propertyToFind){
  var result = [];
  exploreObject(obj, function(key, value, parent){
    if(key === propertyToFind){
      result.push({parent: parent, value: value});
    }
  });
  return result;
}

usage example:

findPropertyByRecursion( myNestedObj, 'search' )

where myNestedObj represents the nested object and search is the target key to find

Answer №2

Utilize the replacer argument within JSON.stringify for optimal results:

function extract_data(obj, property) {
  var output = [];
  JSON.stringify(obj, function(key, value) {
    if (key === property) output.push(value);
    return value;
  });
  return output;
}

Answer №3

Gratitude to everyone for sharing your insights. Your contributions have guided me towards a solution that I find much more satisfying.

traverseObject = function(obj, callback){
    for(prop in obj){
        callback(prop, obj[prop]);
        if(typeof(obj[prop]) == "object"){
            traverseObject(obj[prop], callback);
        }
    }
}

getValuesByKey = function(obj, keyToFind){
    var result = [];
    traverseObject(obj, function(key, value){
        if(key == keyToFind){
            result.push(value);
        }
    });
    return result;
}

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

Troubleshooting the issue: Difficulty in activating Navbar dropdown using Angular and ui-router

I've been struggling with this issue for some time now - trying to make a simple bootstrap navbar dropdown function properly with angular ui-router and ui-bootstrap (1.3.3, the latest version). Below is my current code: <div class="container"> ...

Arrange data in JSON file based on job title (role name) category

My current code successfully outputs data from a JSON file, but I'm looking to enhance it by organizing the output based on the "Role Name". For example, individuals with the role of Associate Editor should have their information displayed in one sect ...

Tips for toggling Bootstrap 5 tabs using JavaScript instead of the button version

I am looking to switch tabs programmatically using bootstrap 5. The Bootstrap documentation recommends using buttons for tabs instead of links for a dynamic change. Here is the code I have: $("#mybut").click(function() { var sel = document.querySelector( ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

Best practices for sharing data between controllers in an Angular application

It appears that this topic has been discussed before, but... While service or events can be used for this purpose, there is conflicting information online about the frequency of using events. Creating a separate service may not be the ideal solution eith ...

Each time the page is reloaded, the Ajax call is triggered, resulting in duplicated

When I visit my homepage, one of the components on the page looks like this: import React, {Component} from 'react'; class BlogPostsWidget extends Component { render() { $.ajax({ type: "GET", url: 'https://example.com/wp- ...

In the React js and emotion framework, fonts are only loaded in production mode after the page has been re

I have set up emotion's Global component to globally apply a font to my app: export const GlobalStyle: FC<{}> = () => ( <Global styles={css` @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;50 ...

What is the process for transforming promises into async await syntax?

login() { return new Promise((resolve, reject) => { userCollection.findOne({email: this.data.email}).then((myUser)=>{ if (myUser && myUser.password == this.data.password) { resolve("Congrats! Succe ...

Encountered an issue while trying to deserialize nested JSON objects

Here is the link to access my nested JSON data: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=AIzaSyDk8ZfHO__XrYfDGi9RnFA_WxlVmRW5HMI I have cr ...

Material UI Snackbar background color not able to be changed

Currently, I'm working on an ErrorHandler component in React.JS that displays a Material UI Snackbar whenever it catches an error. The issue I'm facing is trying to change the background color of the Snackbar to red, which seems to be problematic ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Steps to customize a CSS file within node_modules

Is there a way to make changes to a CSS file in the "node_modules" dependency without them being overwritten when I run npm install? I want to keep the modifications I've made to the node module files. ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Securing uploaded documents and limiting access to approved individuals

Currently, I am utilizing Multer for file uploads and I am contemplating the ideal approach to secure access to these files post-upload. In my system, there are two user roles: admin and regular user. Users can only upload photos while only admins have ac ...

What is the method for obtaining multiple indices on an Array?

Attempting to find multiple index positions in an Array for a Boolean value. Experimenting with while and for loops to iterate through more than one index position without success so far. Below is the code snippet: let jo = [1,2,3,4,5] let ji = [1,2,3] ...

Can you provide guidance on utilizing the Login Event within the Electron Framework?

I need some assistance in understanding the functionality of the Event: 'login' feature within the Electron Framework. Is this similar to the Password Autofill/Remember Password feature typically found in web browsers? I'm interested in util ...

Tips for enabling or disabling elements within an array using React JS

I am looking to develop a feature where I can toggle individual boxes on and off by clicking on them. Currently, only one box at a time can be activated (displayed in green), but I want the ability to control each box independently without affecting the ot ...

Adding elements into a PHP MySQL associative array using the array_push function

Trying to construct an associative array with PHP, utilizing an ajax script that accesses a JSON file. The script was successfully tested with the following PHP code: $testLocs = array( 'loc5' => array( 'info' => 'Some rand ...

Unlock the Power of EmailJS with Vue.js 2 and TypeScript

I couldn't find a similar issue online, so here's my problem. I'm trying to create a form for receiving contact from an app using Vue.js 2 and TypeScript. Here is my code: <form ref="form" class="form-data" @submit.pr ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...