Using JavaScript, implement the array.filter method on a JSON array to retrieve the entire array if a specific property matches a given

Help needed with filtering an array:

In the user_array, there are arrays that need to be compared to see if the header_info.sap_number matches any value in the valid_sap_number array.

If a property value matches anything in the valid_sap_number array, the array and its parent array will be retained, while all other arrays that do not match any value from the valid_sap_number array will be removed. Refer to the example below for clarification.

Example array:

var valid_sap_number = ['1', '2']
var user_array = 
[{
  "name": "User1",
  "header_info": [{ "sap_number": "1" }],
  "footer_info": [{ "site": "ABC" }]
}],
[{
  "name": "User2",
  "header_info": [{ "sap_number": "2" }],
  "footer_info": [{ "site": "ABCD" }]
}],
[{
  "name": "User3",
  "header_info": [{ "sap_number": "3" }],
  "footer_info": [{ "site": "ABC" }]
}];

/* Filter code */

 const result = user_array.filter(user => function(a,b){        
            for(i = 0; i < valid_sap_number.length; i++)
            {
                if(b.header_info[0].sap_number == valid_sap_number[i]){
                    return true;     
                }
            }
        });

    console.log(result); 

Expected output:

result = [{
      "name": "User1",
      "header_info": [{ "sap_number": "1" }],
      "footer_info": [{ "site": "ABC" }]
    }],
    [{
      "name": "User2",
      "header_info": [{ "sap_number": "2" }],
      "footer_info": [{ "site": "ABCD" }]
    }];

Answer №1

To determine if the current item matches any of the values in the list, you can utilize the array's includes function within the filter function.

const result = user_array.filter(user => { 
  return valid_sap_number.includes(user[0].header_info[0].sap_number);
  });

Answer №2

After reviewing your feedback, it appears that there is an opportunity to enhance the structure of the JSON data. The current format may be misleading and not entirely suitable for your needs.

Suggested Proposal:

user_array = [
   {
         "name" : "User1",
         "header_info": {
            "sap_number": 1,
            //... other properties of header_info
         },
         "footer_info" : {
             "site" : "ABC",
             //... other properties of footer_info
         }
   },


{
         "name" : "User2",
         "header_info": {
            "sap_number": 2,
            //... other properties of header_info
         },
         "footer_info" : {
             "site" : "ABCE",
             //... other properties of footer_info
         }
   }

] 

Furthermore, you can create a filter using:

user_array.filter( user => valid_sap_number.includes(user.header_info.sap_number));

Answer №3

Initially, it seems that your user_array is not formatted correctly as an array.

In this scenario, you can utilize the .filter() method to resolve the issue.

Please refer to the code snippet below for a solution:

var valid_sap_number = ['1','2']
var user_array = [
[{
  "name":"User1",
  "header_info": [{ "sap_number":"1" }],
  "footer_info": [{ "site":"ABC" }]
}],
[{
  "name": "User2",
  "header_info": [{ "sap_number": "2" }],
  "footer_info": [{ "site": "ABCD" }]
}],
[{
  "name": "User3",
  "header_info": [{ "sap_number":"3" }],
  "footer_info": [{ "site":"ABC" }]
}]
];

const result = user_array.filter(a => valid_sap_number.includes(a[0].header_info[0].sap_number))

Answer №4

for (const person of user_array) {
    let output = [];
    const employeeID = person.header_info[0].employee_id;
    for (const validID of valid_employee_ids) {
        if (validID == employeeID) {
            output.push(person);
        }
    }
}
user_array = output;

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

Tips for creating incremental progress on a pop-up page?

I am looking for guidance on creating a page with specific functionalities. Here is what I have in mind: I want to implement a button that opens a popup when clicked. The popup should display static instructions and buttons for the user to progress throu ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Best methods for deleting an element's attribute or style attribute

Imagine this snippet of CSS code: .notif-icon { display: inline-block; } In my HTML, I have the following element which starts off hidden by overriding the display property of the notif-icon class: <span id="error" class="notif-icon& ...

Identifying the Correct Data Type of Objects in JSON Using Objective-C

I am facing an issue with my JSON service that deals with registering new users. In case of errors such as "Email in use" or "Taken username," the service returns error codes separated by the "|" character within a string format. However, when the registra ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

Is there a way to parse a JSON file and present its data in a TableView using JavaFX?

This particular concept is causing me some difficulty. I possess a local JSON file labeled customers.json, which houses information on 1000 customers. "Customers": [{ "id": 1, "gender": "female", "fi ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

Using Node.js and Express to retrieve data from a MySQL database and update a table

My .ejs file contains a form that sends data to a MySQL database and then displays two tables with the retrieved data on the same page. However, I am facing an issue where the tables do not refresh after submitting the form, requiring me to restart the ser ...

When attempting to add information, an error occurs stating that the object of type 'dict' does not have the attribute 'append'

Encountered an error: AttributeError: 'dict' object has no attribute 'append'. How can I handle this error when attempting to append data by creating a loop to continuously add values from user input to a dictionary? Is there any method ...

Having trouble connecting a JavaScript file from my local directory to an HTML document. However, when I try to access it in the browser, I keep getting

Currently, I am attempting to connect a javascript file to my html document. Following the directions at this link, I am trying to enable the selection of multiple dates from a calendar as input in a form. The instructions mention that I need to include ...

Problem with Handlebars: When compiling, TypeError occurs because inverse is not recognized as a function

I've hit a roadblock with an error that I just can't seem to solve. My goal is to dynamically compile a template extracted from a div on the page, provide it with content, and then display it in a designated area of my webpage. Here's the s ...

Persist the checkbox value in the database and update the status of the label accordingly

I need a checkbox for user preference selection that is stored in a MySQL database for constant availability. The label should change to "Enabled" when the checkbox is selected and vice versa. Upon saving (submitting) the page, an alert message should disp ...

Enhancing one's comprehension of precompiling JavaScript

var foo=1; function bar(){ foo=10; return; function foo(){} } bar(); alert(foo); As I delve deeper into the inner workings of JavaScript running on the machine, I stumbled upon this code snippet. Despite my best efforts, I am perplexed as to why the ...

Troubleshooting Controller Action Failure in AJAX Request

Hello there I am encountering an issue with my AJAX call not reaching the Controller action in my ASP.NET MVC web application project. Below, you will find my AJAX call written in Javascript and the corresponding Controller's Action. Here is the AJA ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

Error: The script is not found in the package.json configuration

I encountered the following error while trying to execute npm run dev: Error: Missing script: "dev" Error: Error: To view a list of available scripts, use the command: Error: npm run Here is a list of scripts present in my package.json file: "scripts ...

JavaScript Countdown Timer Programming

I've scoured countless resources, but most of them only provide code for counting down to a specific day. I'm reaching out in the hopes that someone can assist me by crafting some JavaScript for the following HTML structure. This section of my w ...