What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it.

Using draggablevue, I have set up a list of arrays that can be sorted. My goal is to keep the main array intact and only filter the "inv" array based on name or code. I've tried using forEach, map, and filter methods, but haven't been able to find a solution online.

let invNameFilter = "chair";
let invCodeNameFilter = "1234";
let rooms = [
        {
          name: "Room 1.14",
          inv: [
            {
              name: "chair",
              inventoryCode: "1234"
            },
            {
              name: "painting",
              inventoryCode: "4321"
            },
            {
              name: "table",
              inventoryCode: "1234"
            }
          ]
        },
        {
          name: "Room 1.12",
          inv: [
            {
              name: "table",
              inventoryCode: "4321"
            },
            {
              name: "chair",
              inventoryCode: "4321"
            }
          ]
        }
      ];
let invNameFilter = "chair";
let invCodeNameFilter = "1234";
let rooms = [
        {
          name: "Room 1.14",
          inv: [
            {
              name: "chair",
              inventoryCode: "1234"
            },
            {
              name: "table",
              inventoryCode: "1234"
            }
          ]
        },
        {
          name: "Room 1.12",
          inv: [
            {
              name: "chair",
              inventoryCode: "4321"
            }
          ]
        }
      ];

Answer №1

To achieve the desired outcome with your existing object structure, a combination of map, filter, and Object spread operations can be utilized.

  • Utilize map (to retain all outer objects)
  • Implement Object spread (for overriding inv while filtering)
  • Apply Filter on inv (use filter function to return the specific results)

const rooms = [
  {
    name: "Room 1.14",
    inv: [
      {
        name: "chair",
        inventoryCode: "1234"
      },
      {
        name: "whiteboard",
        inventoryCode: "4321"
      },
      {
        name: "table",
        inventoryCode: "1234"
      }
    ]
  },
  {
    name: "Room 1.12",
    inv: [
      {
        name: "table",
        inventoryCode: "4321"
      },
      {
        name: "chair",
        inventoryCode: "4321"
      }
    ]
  }
];

const filteredRooms = rooms.map(x => ({
                        ...x, 
                        inv: x.inv.filter(k => k.name === "chair" || k.inventoryCode === "1234") 
                      }))

console.log(filteredRooms);

Answer №2

Take note that this particular code does not alter the initial salas array.

new Vue({
  data() {
    return {
      name: "chair",
      code: "1234",
      salas: [{
          name: "Room 1.14",
          inv: [{
              name: "chair",
              inventoryCode: "1234"
            },
            {
              name: "painting",
              inventoryCode: "4321"
            },
            {
              name: "table",
              inventoryCode: "1234"
            }
          ]
        },
        {
          name: "Room 1.12",
          inv: [{
              name: "table",
              inventoryCode: "4321"
            },
            {
              name: "chair",
              inventoryCode: "4321"
            }
          ]
        }
      ]
    }
  },
  computed: {
    filteredSalas() {
      // Alternatively, you can use _.deepClone (a lodash function)
      const arr = JSON.parse(JSON.stringify(this.salas));

      arr.forEach(obj => {
        obj.inv = obj.inv.filter(item => item.name === this.name && item.inventoryCode === this.code);
      });

      return arr;
    }
  },
  template: "<div>{{ filteredSalas }}</div>"
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

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 to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...

Sinon experiences delays during an AJAX call

I am working with Mocha Chai and Sinon to test a revealing module pattern and encountering a timeout failure. How can I effectively test a method that assigns variables from an AJAX request? Test.js (function () { 'use strict'; describe(&a ...

Struggling to generate a JSON file as a PHP warning keeps popping up

Every time I execute the following code: <?php $array = array_count_values($roles); var_dump($roles); $result = array(); foreach($array as $key => $value) { $result[]=array("name"=>$key,"data"=>$value); } ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

Toggle visibility of cards using bootstrap

I've been attempting to show and hide a selection of cards in bootstrap, but I'm having trouble figuring it out. All the cards share the class "card," and my goal is to hide them all when a specific button is clicked. Below is my current code: ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Issues with template literals not displaying line breaks

I am working with a template literal on node8.1.2 let gameDayReport = `Next 7th Day: ${nextSeventh} ${gameHours} : ${gameMinutes} Day: ${gameDay}` When I view it in my browser, the text appears as a single line instead of retaining the line breaks. It se ...

Having trouble with jQuery attribute selectors? Specifically, when trying to use dynamic attribute

This is the code I am working with $("a[href=$.jqURL.url()]").hide(); $.jqURL.url() fetches the current page URL. Unfortunately, this code is not functioning as expected. Is there a way to dynamically select elements? ...

The parent element of a 3D div is causing issues with hovering and clicking on the child elements

In my scenario, the parent div is transformed in 3D with rotation, causing it to move to the backside. The issue arises with the child div containing a button that becomes unclickable due to the parent div position. Setting backface-visibility to hidden al ...

Guide to utilizing Vue-Router and Gorilla Mux Router simultaneously

Currently working on a web app with Vue JS as the front end framework and using Vue-Router for routing paths to my vue components. To serve this web app, I've chosen Go with gorilla mux as the router. The issue I'm facing is not being able to lo ...

How can I integrate Apple remote support into a website with the use of Javascript?

One thing that I find interesting is the ability to use the Apple remote with Front Row, as well as other apps on Mac that support it. I'm curious about whether Web Apps could also be made compatible through Javascript. I have a concept for a TV-like ...

Using AngularJS to send a post request with cherrypy

I am facing an issue with posting events into a CherryPy small application that responds to GET/POST requests. When attempting to do so using AngularJS, nothing gets posted. I'm unsure if the problem lies with AngularJS or CherryPy (CP). Cross-domain ...

Improving iframe functionality in AngularJS

I've been experimenting with AngularJS to dynamically update an iframe whenever a query is triggered. It works like this: a query is made, the embed link is fetched from the database, and then it's used in the iframe alongside the title and video ...

Manipulating binary data through the use of encodeURIComponent

Currently, I am reading a binary file by making a jQuery ajax get request. The file (a zip file in this instance) is returned as a string. After performing some actions on the file within the browser without modifying it, I need to send it back to a server ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Difficulty loading AngularJS 1.3 page on Internet Explorer 8

Being an avid user of Angular, it pains me to even bring up the topic of IE8, a browser that many consider to be pure evil and deserving of extinction. Despite my reservations, I am experiencing difficulties with loading Angular 1.3 in IE8. The page break ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

Is there an issue with loading Vue list rendering due to Axios not returning the data?

Utilize the axios request api interface to fetch data and populate a list, but encounter a problem when trying to iterate through the properties of an object using v-for. Take a look at the javascript snippet below: var vm = new Vue({ el: '# ...