Tips for sorting through a deeply nested array of objects based on specific values and retrieving the parent object

I am facing an issue with filtering a JSON object that contains nested arrays and objects. Here is an example of the structure:

[
  {
    name: 'data 1',
    users: [
      {
        username: 'user 1',
        full_name: 'name 1',
        sources: [
          { type: 'type 1', name: 'source name 1' },
          { type: 'type 2', name: 'source name 2' },
        ],
      },
      {
        username: 'user 2',
        full_name: 'name 2',
        sources: [
          { type: 'type 3', name: 'source name 3' },
          { type: 'type 4', name: 'source name 4' },
        ],
      },
    ],
  },
  ...
];

I need a function that can filter this data recursively based on all its values. For example, if I search for "data 1", it should return only the object containing "data 1" like so:

[
  {
    name: 'data 1',
    users: [...],
  },
];

Similarly, searching for "source name 3" should return both "data 1" and "data 2" objects in an array.

I have tried implementing a recursive search function but it returns all data instead of just the filtered data. The function looks like this:

function search(data) {
  return data.filter((data) => {
    // Implementation logic for recursive search
  });
}

While it's easy to filter by a specific key, dynamically filtering by all keys poses a challenge. What approach should I take to successfully filter this JSON object?

Answer №1

One possible solution is to implement a recursive function that iterates through the values of an object.

const
    has = value => object => Object
        .values(object)
        .some(v => v === value || v && typeof v === 'object' && has(value)(v)),
    filter = (array, value) => array.filter(has(value)),
    data = [{ name: 'data 1', users: [{ username: 'user 1', full_name: 'name 1', sources: [{ type: 'type 1', name: 'source name 1' }, { type: 'type 2', name: 'source name 2' }] }, { username: 'user 2', full_name: 'name 2', sources: [{ type: 'type 3', name: 'source name 3' },   { type: 'type 4', name: 'source name 4' }] }] }, { name: 'data 2', users: [{ username: 'user 3', full_name: 'name 3' }, { username: 'user 4', full_name: ' name 4', sources: [{ type: 'type 5', name: 'source name 3' }, { type: 'type 6', name: 'source name 5' }] }] }, { name: 'data 3', users: [{ username: 'user 5', full_name: 'name 5' }, { username: 'user 6', full_name: 'name 6', sources: [ { type: 'type 5', name: 'source name 6' }, { type: 'type 6', name: 'source name 7' }] }] }];

console.log(filter(data, 'data 1'));
console.log(filter(data, 'source name 3'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

Inserting only the initial three values into the MySQL Workbench from Next.js

My app.js file has the following code: app.post('/api/add-order-cui', async (req, res) => { const { cui, email, phone, billingCUI, // Add other fields if necessary } = req.body; console.log('Received request body:&a ...

Issues have been reported with Safari mobile on iOS version 10.2.1 where CSS links are not being detected

I am in the process of creating a website using HTML, PHP, JavaScript, and CSS. All three languages are included in the same document with a link to an external CSS file. As I test for browser compatibility, I discovered that Safari on iOS 10.2.1 is unable ...

Incorporate dynamic variables into your HTML code using jQuery or JavaScript

I'm struggling to generate HTML code from JavaScript/jQuery within an HTML template rendered in Django. I need to append HTML code and also insert some values in between. Currently, I am using a basic string append method like this: var features =[&ap ...

Is there a way I can modify the display setting to show 4 slides per view?

var swiper = new Swiper(".new-arrival", { slidesPerView: 4, centeredSlides: false, spaceBetween: 30, autoplay: { delay: 5500, disableOnInteraction: false, }, pagination: { el: ".swiper-pagination", type: &qu ...

Access values of keys in an array of objects using TypeScript during array initialization

In my TypeScript code, I am initializing an array of objects. I need to retrieve the id parameter of a specific object that I am initializing. vacancies: Array<Vacancy> = [{ id: 1, is_fav: this.favouritesService.favourites.find(fav = ...

Create custom error messages for loopback instead of using the default ones

I am attempting to customize the default error messages provided by loopback. Here is my approach: server/middleware.json: { "initial:before": { "loopback#favicon": {} }, "initial": { "compression": {}, "cors": { "params": { ...

Can you explain the concept of binding and unbinding in jQuery?

Can you explain the concepts of binding and unbinding in jQuery in simple terms for someone who learns slowly? ...

Retrieve JSON data from a Postgres table without including field names

Is there a way to convert Postgres table data into JSON without repeating field names in the JSON result? Currently, when using PostgreSQL's json functions, the output looks something like this: [{"id":"1234","name":"XYZ"},....]. However, having all f ...

Is it possible to retrieve a pointer to a one-dimensional struct function that contains multiple different internal structs?

I'm facing an issue with a function that is supposed to return a pointer to a 1-dimensional array of multiple structs (65,535 in this case). However, it only returns the first element of the array. I'm puzzled and trying to figure out what's ...

Interchanging information between Express and AngularJS

Using AngularJS, I have a data file through which I connect with the database. However, I am facing an issue in sending the frontend data to the backend. Can anyone provide assistance? app.get('/api/data/:id', function (req, res) { res.json ...

Saving fonts when deploying on Vercel with Next.js is not supported

Troubleshooting Differences in Local Viewing and Deployment: https://i.stack.imgur.com/jktPN.png When viewing locally, everything appears as expected. However, upon deploying, there are noticeable discrepancies. https://i.stack.imgur.com/NKQQ6.png Even ...

Organize Divs - Arrange each div below its corresponding image using JavaScript and jQuery

Here is a sample structure I am working with: <div class="main"> <div class="image">Image1</div> <div class="image">Image2</div> <div class="image">Image3</div> & ...

Error: The module '/@modules/vue.js' does not export a 'default' value as requested by the syntax

I'm encountering an issue with Vee Validate form validation in Vue.js. As a beginner, I am struggling to grasp the import syntax. After installing vee-validate using npm i vee-validate --save and placing it in my node_modules directory, I proceeded to ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Optimal method for showcasing a menu featuring items stored in arrays

I'm in the process of developing an Android application where, upon completion of all code, I will receive an integer array. Let's assume it contains the numbers 3, 5, and 24. I also have two other arrays named array1 and array2. My goal is to de ...

The initial time delay set by setTimeout does not seem to have any impact

The issue with setTimeout not working as expected lies in its execution order. The code below it gets executed without waiting for the delay specified in the first argument of 'setTimeout' to run. (function() { var a = ['#bird',&ap ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Sending a javascript variable to an angularjs scope

Currently, I am utilizing Flask to render an HTML template and wish to transfer the variable add_html_data, which is passed via Flask's render_template, to the scope of an AngularJS controller. I have attempted the following: <body> <di ...