Tips for filtering data using an array within an object containing arrays

Below is the provided information:

userRoom = ['rm1'];

    data = [{
      name: 'building 1',
      building: [{
       room: 'rm1',
       name: 'Room 1'
      },{
       room: 'rm2',
       name: 'Room 2'
      }]
     },{
      name: 'building 2',
      building: [{
       room: 'rm3',
       name: 'Room 3'
      }]
     },{
      name: 'building 3',
      building: [{
       room: 'rm1',
       name: 'Room 1'
      }]
     }]

The objective here is to display the data that includes a building with room1 and apply a filter.

The expected result should look like this:

 [{
      name: 'building 1',
      building: [{
       room: 'rm1',
       name: 'Room 1'
      },{
       room: 'rm2',
       name: 'Room 2'
      }]
     },{
      name: 'building 3',
      building: [{
       room: 'rm1',
       name: 'Room 1'
      }]
     }]

I attempted to achieve this by utilizing the following code snippet:

data.map(x => x['building'].filter(y=> userRoom.includes(y.room));

However, I encountered issues with its functionality.

Answer №1

In my earlier comment, I suggested utilizing the filter, followed by some, and then includes for a more organized solution:

userRoom = ['rm1'];

data = [{
  name: 'building 1',
  building: [
    { room: 'rm1', name: 'Room 1' },
    { room: 'rm2', name: 'Room 2' }
  ]
}, {
  name: 'building 2',
  building: [
    { room: 'rm3', name: 'Room 3' }
  ]
}, {
  name: 'building 3',
  building: [
    { room: 'rm1', name: 'Room 1' }
  ]
}];

let filtered = data.filter(i => 
  i.building.some(j => 
    userRoom.includes(j.room)));

console.log(filtered);

This approach works effectively due to:

  • The need to selectively filter the entries in the data array based on specific criteria.
  • For a building to pass the filtering process, at least one room within it must match certain conditions as determined by the some function.
  • The condition being that the room's identifier must be part of the userRoom array, hence the usage of includes.

Answer №2

Using Array.map won't work in this scenario, as it always returns a node for each element in the input array. Consider using a different method of iteration.

Instead, you can achieve the desired outcome by combining Array.filter with Array.some.

const userRoom = ['rm1'];
const data = [{"name":"building 1","building":[{"room":"rm1","name":"Room 1"},{"room":"rm2","name":"Room 2"}]},{"name":"building 2","building":[{"room":"rm3","name":"Room 3"}]},{"name":"building 3","building":[{"room":"rm1","name":"Room 1"}]}];
const output = data.filter((curr) => curr['building'].some(y=> userRoom.includes(y.room)));
console.log(output);

To solve this problem, apply a filter on the data array based on specific conditions.

Your condition is valid, so utilize Array.some to filter the data accordingly.

Answer №3

Implementing some, filter, and includes

const data = [{"name":"building 1","building":[{"room":"rm1","name":"Room 1"},{"room":"rm2","name":"Room 2"}]},{"name":"building 2","building":[{"room":"rm3","name":"Room 3"}]},{"name":"building 3","building":[{"room":"rm1","name":"Room 1"}]}];

const anyUserRoomInBuilding = 
(building, userRoom) => building.some(({room}) => userRoom.includes(room));

const getBuildingsByUserRoom = 
(data, userRoom) => data.filter(({building}) => anyUserRoomInBuilding(building, userRoom))

console.log(getBuildingsByUserRoom(data, ['rm1']));

// console.log(getBuildingsByUserRoom(data, ['rm3', 'rm1']));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Answer №4

const filteredData = data.filter(item => {
  return item.building.filter(buildingItem => {
    return userRooms.includes(buildingItem.room);
  }).length > 0;
});

userRooms = ['rm1'];

data = [{
  name: 'building 1',
  building: [{
    room: 'rm1',
    name: 'Room 1'
  }, {
    room: 'rm2',
    name: 'Room 2'
  }]
}, {
  name: 'building 2',
  building: [{
    room: 'rm3',
    name: 'Room 3'
  }]
}, {
  name: 'building 3',
  building: [{
    room: 'rm1',
    name: 'Room 1'
  }]
}]

const filteredData = data.filter(item => {
  return item.building.filter(buildingItem => {
    return userRooms.includes(buildingItem.room);
  }).length > 0;
});

console.log(filteredData);

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

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

Using Vue.js to send user input data to a different page and trigger a method for submission

I am seeking assistance with my first question and hope to receive your support. In my setup, I have a catalogue page that includes a keyword search function and a main page with a search bar. My objective is to automatically redirect any submission from ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Button on aspx page not functioning properly when clicked

I seem to be experiencing an issue with buttons. To check if the function is being triggered, I used alert("") and found that it does enter the function when the button is clicked. However, after the alert, any other code inside the function seems to not w ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

How can I modify the appearance of a slider's range?

I'm struggling with customizing the style of a price slider input range. No matter what I do, the changes don't seem to take effect. Can anyone pinpoint where I may be going wrong? Appreciate any guidance on this! Thank you! <div class=" ...

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

When trying to use the `map: texture` with a new `THREE.Texture(canvas)

i'm trying to apply the texture from new THREE.Texture(canvas) to the PointsMaterial, but it's not working as expected. The canvas appears on the top right corner, however, only white points are visible in the CubeGeometry. var texture = new ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

Eliminate any unnecessary padding from elements in angular2 components

Is there a way to remove the automatic padding added to new components in angular2? I am facing this issue with the header of my project, as shown in the image below: https://i.sstatic.net/25Zpn.png I attempted to eliminate the padding by setting it to 0 ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...

Unable to retrieve base64 pdf file due to network connectivity problem

I am trying to download a base64 pdf file from local storage using vue3 typescript. Here is the code snippet I'm using: downloadPDF() { const linkSource = `data:application/pdf;base64,${'json.base64'}`; const downloadLink = ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

The process of displaying only the month name as the title in Full Calendar

Is there a way to display the Full Calendar title with only the month name instead of "month name year name"? Here is my code attempt: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title' ...

Looking to make some changes to the javascript countdown script

Hello, I have come across a JavaScript countdown timer code on stackoverflow that seems to be the perfect solution for my countdown timer project. The current code counts down from 30 minutes to 1 minute and then starts over again. However, it provides the ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

Is there any importance to port 9229 and is it possible to modify it?

In my initial training, it was always recommended to run a local Node server on port 3000. However, after learning about the Chrome Node debugger in a tutorial that uses port 9229, I decided to switch to this port. For more information on port 3000, you ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...