Trying to save the array returned from Object.keys(obj) into a variable in JavaScript but encountering the error message "ReferenceError: array is not defined"

I'm struggling with this code and can't seem to figure out what's wrong. For some reason, the line "arrKeys = Object.keys(source);" is not returning the array as expected.

function findMatchingValues(collection, source) { 
var arr = [];                    // should return an array of properties and values found in the object
var arrkeys = [];
arrKeys = Object.keys(source);   // should return ["last"] 
var test = false;
// Loop through the collection array object and search for objects that match the second argument passed to the method
for(var i = 0; i < collection.length; i++){    
for(var j = 0; j < arrKeys.length; j++){
  if(collection[i].hasOwnProperty(arrKeys[j])){
      if(collection[i][arrKeys[j]] ===  source[arrKeys[j]]){
        test = true;
      }else{
          break;
      }
  } else{
      break;
   }
    if(j === (arrkeys.length - 1) && test === true){
      arr.push(collection[i]);
      } 
    }// end of inner for loop   
  }// end of outer for loop
 return arr; 
}

findMatchingValues([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",   last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Answer №1

There are a few errors in your code

var arrKeys = [];
//     ^

if(j === (arrKeys.length - 1) && test === true){
//           ^

function findProperties(collection, source) {
    var arr = [];                    // This function should return an array of properties and values found in the collection object
    var arrKeys = Object.keys(source);   // For example, this will return ["last"] 
    var test = false;
    // Loop through the collection array object to search for objects that match the second argument passed to the function
    for (var i = 0; i < collection.length; i++) {
        for (var j = 0; j < arrKeys.length; j++) {
            if (collection[i].hasOwnProperty(arrKeys[j])) {
                if (collection[i][arrKeys[j]] === source[arrKeys[j]]) {
                    test = true;
                } else {
                    break;
                }
            } else {
                break;
            }
            if (j === (arrKeys.length - 1) && test === true) {
                arr.push(collection[i]);
            }
        }// end of inner for loop   
    }// end of outer for loop
    return arr;
}


console.log(findProperties([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));

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

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

Discover how to retrieve the calculated percentage within CSS with the assistance of jQuery specifically designed for Webkit

I'm currently working on a simple sliding animation. However, the div that slides in is utilizing percentages for its width and right positioning. The issue arises specifically in Webkit browsers. When using jQuery to retrieve the value, it returns t ...

Perform an AJAX request to an encrypted URL with an unverified certificate

I'm experiencing an issue with my site that makes AJAX JSONP calls to a secured (SSL) web server. Everything works smoothly when using an unsecured (HTTP) web server, but once I switch to the SSL version, the call never returns. After checking with Fi ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Identify the top ten largest numbers in a C array

How can I efficiently extract the largest ten numbers from an array of integers in C, where the length of the array can range from 11 to 500? To start, consider the following code snippet: arrayNumbers[n]; //array containing input numbers, 11<n<500 ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

Automatically formatting text upon entering it in Vue.js

I need assistance with auto-formatting the postal code entered by the user. The rule for the postal code is to use the format A0A 0A0 or 12345. If the user inputs a code like L9V0C7, it should automatically reformat to L9V 0C7. However, if the postal code ...

Transferring information between two separate components

Hey there, I'm struggling with the Payment Component. What I want to achieve is that when I click on a link, it transfers (ClassG, imageG, and PriceG) to the Payment Component where I can then style them accordingly. I've attempted something, but ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

Having trouble integrating Ionic Native API and Javascript API in one application?

Currently, I am developing an application using Google Maps that utilizes both the Ionic Native Google Maps API and the JavaScript version. The Native API is implemented on a page called home.ts, while the JavaScript API is utilized on a sub-page called de ...

Adding and removing dynamic fields with Bootstrap functionality

Recently, I've been trying to develop a feature where users can add and remove fields by clicking on a button. However, I've encountered a roadblock in my progress. If you take a look at this CodePen link, you'll see what I have so far. My a ...

Next.js Configuration Files Explained

Currently, my application is functioning well with the use of Next.js and Next.js API tool for handling requests. The backend is managed through sanity.io which is working smoothly. In my sanity configuration setup, I have a dedicated file named 'san ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Can anyone recommend a drag-and-drop feature in Javascript that functions seamlessly on both iPad and PC devices?

Can anyone recommend a JavaScript plugin that allows for drag and drop functionality on both touch and mouse enabled devices, including IOS, Android, PC, and Mac? For touch-enabled devices, I found an example here: And for mouse-enabled devices, there is ...

Icon button not found

I have created a reusable hook component for input fields. The TextField renders perfectly, but the IconButton is not showing up. const InputHookComponent = (props) =>{ const [val, setval]=useState(""); const cmp = <TextField type={ ...

The art of effectively conveying arguments to the callback function

Here's a react App component that takes in a settingsobj object along with a callback function: export const settingsObj = { handlers: { onClick: (e, dispatch) => { console.log('Click event triggered from settingsObj', e); dispat ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...