Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows:

var items = [
{   "id" : 1,
    "title" : "this",
    "groups" : [
        {"id" : 1,
        "name" : "groupA"},
        {"id" : 2,
        "name" : "groupB"}
    ]
},
{   "id" : 2,
    "title" : "that",
    "groups" : [
        {"id" : 1,
        "name" : "groupA"},
        {"id" : 3,
        "name" : "groupC"}
    ]
},
{   "id" : 3,
    "title" : "other",
    "groups" : [
        {"id" : 3,
        "name" : "groupC"},
        {"id" : 2,
        "name" : "groupB"}
    ]
}]

My goal is to filter this data based on group ids, but I'm encountering issues with accessing them - when trying item.group, the entire object is returned, and other attempts like item.groups.id result in null or undefined values.

I would greatly appreciate any guidance or suggestions on how to achieve this. Essentially, I aim to filter the array to include all items that belong to a specific group.

Thank you!

Answer №1

Consider this solution:

groupThreeItems = items.filter(item => item.groups.findIndex(group => group.id==3) > -1)

Answer №2

Here is an example of how you can achieve this:

var items = [{
  "id": 1,
  "title": "this",
  "groups": [{
    "id": 1,
    "name": "groupA"
  }, {
    "id": 2,
    "name": "groupB"
  }]
}, {
  "id": 2,
  "title": "that",
  "groups": [{
    "id": 1,
    "name": "groupA"
  }, {
    "id": 3,
    "name": "groupC"
  }]
}, {
  "id": 3,
  "title": "other",
  "groups": [{
    "id": 3,
    "name": "groupC"
  }, {
    "id": 2,
    "name": "groupB"
  }]
}]

// Create a function to filter out the matched value
function filterArray(array, val) {
  return array.filter(function(elem) {
    return elem.id === val; // Filter by Id
  })
}

// Filter the original items array and get the object where id is 1
var obj = filterArray(items, 1);
// As the previous result is an array, access the first index with obj[0]. 
// Then, obj[0].groups will be an array again

var filterGroup = filterArray(obj[0].groups,1) // Get an array containing the matched group

Check out the DEMO here.

Answer №3

Utilize:

  1. Array.prototype.map to generate a new array by mapping each item in the array to a new object by
  2. duplicating each item using the spread operator* and replacing the groups key with a new array created from the original using
  3. Array.prototype.filter to retain only the objects with the correct id.

*requires a transpiler like babel or typescript though

OR

If you desire to simplify the structure, then you could use Array.prototype.reduce to combine the arrays.


The code provided below gives two results:

  1. one maintains the original structure but filters out the items in the group that do not have an id of 3.
  2. one flattens the structure and displays just one array.

const items = [{
    "id": 1,
    "title": "this",
    "groups": [{
        "id": 1,
        "name": "groupA"
      },
      {
        "id": 2,
        "name": "groupB"
      }
    ]
  },
  {
    "id": 2,
    "title": "that",
    "groups": [{
        "id": 1,
        "name": "groupA"
      },
      {
        "id": 3,
        "name": "groupC"
      }
    ]
  },
  {
    "id": 3,
    "title": "other",
    "groups": [{
        "id": 3,
        "name": "groupC"
      },
      {
        "id": 2,
        "name": "groupB"
      }
    ]
  }
];

const filteredRemovingGroups = items.map(item => ({
   ...item,
   groups: item.groups.filter(subItem => subItem.id === 3)
}));

const filterAndFlatten = items.map(item =>
  item.groups.filter(subItem => subItem.id === 3)
).reduce((combinedArr, arr) => [...combinedArr, ...arr], []) 

console.log('filteredRemovingGroups', filteredRemovingGroups);
console.log('filterAndFlatten', filterAndFlatten);

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

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

The video.play() function encountered an unhandled rejection with a (notallowederror) on IOS

Using peer.js to stream video on a React app addVideoStream(videoElement: HTMLVideoElement, stream: MediaStream) { videoElement.srcObject = stream videoElement?.addEventListener('loadedmetadata', () => { videoElement.play() ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

Create a new element by cloning the React component as an SVG named SomeSVG

I have a scenario where I am receiving an SVG as a prop in my child component. Once I receive it, I would like to manipulate it by adding some additional properties like this: {React.cloneElement(ReactSVGasProp, { className: class })} However, when I atte ...

Find the sum of every combination of numbers in the array

I've reviewed my code countless times and I'm stumped by the issue. My code is designed to calculate all possible sums of numbers within an array. It works perfectly when there are only 3 numbers in the array, but once I add a fourth number, it i ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

Finding common elements between two arrays through partial matching

Imagine I have two arrays: var array_full = ['table', 'sleeping', 'data']; var array_part = ['sleep', 'able']; My goal is to extract items from the full string array (array_full) that do not contain any e ...

Having trouble with vscode [ctrl+click] on 'vue single-file components' and 'go to definition'? It's not working for me

// src/ui/tabbar/Index.vue <template> <div> my-tabbar component here </div> </template> // src/ui/index.js import MyTabbar from './tabbar/Index.vue' export default { install(Vue) { Vue.component(MyTabbar.na ...

How do you handle an object of a specific type that can only be determined at runtime?

Here's a query I have: We're working on an ASP.NET web application that is designed to cater to multiple clients. The crucial aspect is the app's need to transform specific JSON strings into .NET object of type <T> so that it can be p ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

"Error alert: The specified property 'Iscontains' cannot be read because it is undefined" appears in the script for this video

I am currently utilizing AJAX to interact with my backend code. I retrieve URLs from the database and then render them onto the DOM, displaying videos accordingly. However, I am encountering an issue where Uncaught TypeError: Cannot read property ' ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

Performing two API calls using Jquery to fetch distinct dynamic elements within two nested $.each loops

There's an API link that contains crucial data about phone brands. From this initial data, I have to create a second API call for each brand to gather more detailed information. For example, the first JSON file (urlphonebrands) lists 3 phone brands - ...

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...

Ways to eliminate unnecessary quotation marks surrounding a string in a JSON file using a shell script

I need help removing extra quotation marks from the following JSON data: {""id"":""1"", ""name"":""john"",""address"":"",""timestamp"":""2018/01/01 12:43:42 -700"",""dept"":""} To address this issue, I have been using the sed command: sed -i -e 's/ ...

What could be the reason for the malfunction of the select (mongoose query)?

I'm trying to retrieve a User's highest score post. To accomplish this, I am querying the Post model and looking for posts where their user._id matches the author in the post. Everything is functioning correctly in this regard. However, my goal ...

Can anyone explain the functionality of passport.initialize() in the context of Node.js and Express

I am currently working on implementing the passport module in my application. After reading some manuals, I found this: app.use(passport.initialize()); app.use(passport.session()); Can someone explain what app.use(passport.initialize()) does exactly? I ...

Passing PHP array to JavaScript in a specific format

After running the code provided, I find that the data returned is in an array format but unfortunately not easily referenced. AJAX: $.ajax({ url: './FILE.php', type: 'post', data: {'action': 'allfolders'}, ...

What is the best way to retrieve an object from a POST request using Angular AJAX calls in a NODEJS environment?

When the button is clicked, a method will be called. The code for this is as follows: .controller('templeDetailsList', function ($scope, $http, $ionicModal) { $scope.starclick = function(){ var newFav = [{ ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...