Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data.

This inquiry tackles the challenge of extracting all values from an array based on an object value.

What sets this question apart from the previous one is that it requires fetching all objects based on a value found inside a nested array.

[  
   {  
      "id":111222,
      "name":"Faye",
      "age":27,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":3,
            "name":"eating"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Bobby",
      "age":35,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":4,
            "name":"online gaming"
         }
      ]
   }
]

Answer №1

const hasInterest = (user, interestId) => {
  return user.interests.some((interest) => {
    return interest.id === interestId;
  });
}

const filterByInterest = (users, interestId) => {
  return users.filter((user) => {
    return hasInterest(user, interestId);
  });
}

If you prefer the new, trendy ES6 syntax:

const filterByInterest = (users, interestId) => {
  return users.filter(
    (user) => user.interests.some(
      (interest) => interest.id === interestId
    )
  );
}

Answer №2

const data = [  
   {  
      "id":111222,
      "name":"Faye",
      "age":27,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":3,
            "name":"eating"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Bobby",
      "age":35,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":4,
            "name":"online gaming"
         }
      ]
   }
];

const filteredData = data.filter(function(person) {
 let hobbies = person.hobbies;
 let hasHiking = hobbies.some(function(hob) {
     return hob.id === 2;
});

return hasHiking;
});

Answer №3

Here's a potential solution for your issue:

const people = [{
  "id": 111222,
  "name": "Faye",
  "age": 27,
  "hobbies": [{
    "id": 2,
    "name": "hiking"
  }, {
    "id": 3,
    "name": "eating"
  }]
}, {
  "id": 223456789001,
  "name": "Bobby",
  "age": 35,
  "hobbies": [{
    "id": 2,
    "name": "hiking"
  }, {
    "id": 4,
    "name": "online gaming"
  }]
}];
const filteredPeople = people.filter(person => {
  const hasHikingHobby = person.hobbies.some(hobby => hobby.id === 2);
  return hasHikingHobby;
});
alert(filteredPeople.length);

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

TextView influenced by Res/Arrays

My current task involves populating a listview with data from a JSON object, which is working properly. setListAdapter(new ArrayAdapter<String>(this, R.layout.list_items, name){ @Override public View getView(int position, View co ...

Ways to extract the maximum value from a dataset formatted in JSON

My current project involves using highcharts to create data series for plotting the chart, which looks something like this: series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] I have been considering ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

Decoding Multiple JSON Links

I'm currently working on parsing multiple JSON URLs in my application and displaying them in a single list view. However, I'm only able to display one URL at a time and I want to show multiple URLs with the same array names and attributes in one ...

Guidelines for leveraging AngularJS Decorators to deactivate a button within an Html document

Currently, I am utilizing the blur admin theme and exploring the possibility of using decorators to hide a button without directly modifying the HTML. Despite my efforts, I have been unable to successfully conceal the button. Can someone provide guidance o ...

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

What distinctions can be observed between interacting with the Jira Rest API manually compared to through programming?

Just starting out with Jira Rest APIs...I'm looking to log in to my Local Jira server using a VBA program. While I can successfully access the REST API manually and receive the JSON response I need, I keep encountering an error whenever I try to do it ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

Calculating totals in real-time with JavaScript for a dynamic PHP and HTML form that includes quantity,

I have created a dynamic form with fields and a table that adjusts based on the number of results. Each column in the form represents name, quantity, price, and total price. The PHP and SQL code runs in a loop to populate the list depending on the number ...

Swap out all hyperlinks on the webpage with a different URL

I am looking to update all links in a specific style with new ones. I want to streamline the download process for Google Drive links. https://drive.google.com/file/d/1cCIWJMBOX-NvzYVTQajaVo5lNknYA2E8/view?usp=sharing My plan is to extract '1cCIWJMBO ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Looping through items using ng-repeat according to the chosen option in a select dropdown

After expanding my project, I encountered an issue with the main object structure: { screens: [{ id: 0, name: 'Screen0', sections: [{ id: 0, sectionItems: [] }, { id: 1, sectionItems: [] }, { i ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

Is there a way to toggle a single Reactstrap Collapse component?

Currently, I am working on a Next.JS application that displays a list of Github users. The goal is to have each user's information box toggle open and close when clicked, using Reactstrap's Collapse component. However, the issue I'm facing i ...