Uncover the mystery that lies within the unknown depths

Having the JSON data below:

var lists = [{
        "listId": 1,
        "permission": "WRITE"
    }, {
        "listId": 2,
        "permission": "WRITE"
    }, {
        "listId": 2,
        "permission": "READ"
    }, {
        "listId": 3,
        "permission": "READ"
    }, {
        "listId": 3,
        "permission": "WRITE"
    }, {
        "listId": 5,
        "permission": "WRITE"
    }]

As well as this one:

var arr = [{
    "listId": 1,
    "confidentiality": "PUBLIC",
    "listName": "List name here..1",
    "permission": "WRITE"
}, {
    "listId": 2,
    "confidentiality": "PUBLIC",
    "listName": "List name here..2",
    "permission": "READ"
}, {
    "listId": 3,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..3",
    "permission": "WRITE"
}, {
    "listId": 4,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..4",
    "permission": "WRITE"
}, {
    "listId": 5,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..5",
    "permission": "WRITE"
}]

The task at hand is to filter data from arr and push it to results[] if there is a match in listId and permission within lists[...].

var result = [];

for(var i = 0; i < arr.length; i++) {   
  for(var j = 0; j < lists.length; j++) {     
     if( (arr[j].listId == lists[i].listId) && (arr[j].permission == lists[i].permission) ) {
        result.push(arr[j]);
     }
  }
}
console.log(result);

The issue arises when I encounter listId undefined if arr.length is smaller than lists.length.

Any suggestions on how to tackle this problem?

Answer №1

If the length of arr is smaller than lists, I encounter an issue where listId becomes undefined

To resolve this problem, ensure that you are using the correct indexes for each array - use i for arr and j for lists

if( (arr[i].listId == lists[j].listId) && (arr[i].permission == lists[j].permission) )

Answer №2

A potential optimization could involve restructuring the code to utilize a lookup table for permissions, streamlining the process by employing just a single loop to handle the result set.

var lists = [{ listId: 1, permission: "WRITE" }, { listId: 2, permission: "WRITE" }, { listId: 2, permission: "READ" }, { listId: 3, permission: "READ" }, { listId: 3, permission: "WRITE" }, { listId: 5, permission: "WRITE" }],
    array = [{ listId: 1, confidentiality: "PUBLIC", listName: "List name here..1", permission: "WRITE" }, { listId: 2, confidentiality: "PUBLIC", listName: "List name here..2", permission: "READ" }, { listId: 3, confidentiality: "CONFIDENTIAL", listName: "List name here..3", permission: "WRITE" }, { listId: 4, confidentiality: "CONFIDENTIAL", listName: "List name here..4", permission: "WRITE" }, { listId: 5, confidentiality: "CONFIDENTIAL", listName: "List name here..5", permission: "WRITE" }],
    permissions = {},
    result;

lists.forEach(function (p) {
    permissions[p.listId] = permissions[p.listId] || {};
    permissions[p.listId][p.permission] = true;
});

result = array.filter(function (a) {
    return permissions[a.listId] && permissions[a.listId][a.permission];
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

State not properly updating in the most recent version of Next.js

"use client"; import { useState , useEffect } from "react"; import React from 'react' function form() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [disable, ...

There is no response from Ajax

I am facing an issue with my AJAX call in communication with my Rails controller. Even though the AJAX call itself seems fine, the callback function does not contain any data. Here is the AJAX request I'm making: $.ajax({ url: '/get_progres ...

Script designed to track modifications on a specific webpage

Attempting to purchase items online has become a frustrating challenge as stock seems to disappear within minutes of being added :/ I am currently working on creating a custom grease/tampermonkey script to monitor the page and notify me when products beco ...

Top technique for creating a unique cursor image for a website

I'm looking for the most efficient way to create a custom cursor image for my CSS/HTML5 website without using Flash. Ideally, I would like to implement this using CSS rather than resorting to Javascript. If Javascript is necessary, I want to know whic ...

Extracting cache-control header value from server response

Looking to interpret the cache-control header response in order to utilize it for caching the API response. Here is an example of the response headers: {"x-backside-transport":"OK OK","connection":"close","transfer-encoding":"chunked","access-control-all ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

Tips for creating a validation section in a CRUD application using React.js

I have been working on developing a CRUD app using ReactJS. However, I am facing some challenges with the validation process as it does not seem to be working correctly and I am not receiving any results. As a beginner in this field, I would greatly apprec ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

Are getter and setter pairs permitted to override properties in the base class of JavaScript/TypeScript?

Recently, there has been an update in TypeScript that triggers a compilation error when attempting to override a property in the base class with a getter/setter pair. This issue arises from property access augmentation: class BaseClass { prop : ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

Initiate the initial setup in React using the useEffect function

My main component always requires retrieving a token before the subcomponents can be executed. According to a thread on Stack Overflow about the correct order of execution of useEffect in React parent and child components, it was noted that the subcomponen ...

Inspecting element value on a website

On a marketplace website, I extracted the attribute (capacity_gold) from a table. Since the values are dynamic and constantly changing, I aim to develop a basic script that will notify me when the attribute value exceeds 100. The current value of the attr ...

Utilizing jQuery's .slidedown alongside Prototype's .PeriodicalUpdater: A Comprehensive Guide

I am currently working on creating an activity stream that automatically updates with the latest entries from a database table every time a new row is added. Right now, I am using Prototype's Ajax.PeriodicalUpdater to continuously check for new entri ...

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Is it possible to utilize ajax for submitting a form only after it has been validated by the

Currently, I am utilizing a jQuery plugin for validation and incorporating AJAX for form submission. My objective is to submit the form only after successful validation; however, the issue arises where the form gets submitted regardless of the validation o ...

Utilizing AJAX in Django applications

I'm currently working on integrating a basic AJAX function with Django, but I seem to be facing some issues. The request.is_ajax() function is returning False, and using event.preventDefault() doesn't prevent the form from getting submitted. Her ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...