Struggling to locate the index of the matching object within an array of objects?

There is a dataset available:

var data = {
  "variants": [{
      "quantity": "20",
      "varientId": 8,
      "currency": "YEN",
      "extraField": {
        "Size": "10",
        "Color": "Red",
        "Material": "Denim"
      },
      "price": "199"
    },
    {
      "quantity": "15",
      "varientId": 10,
      "currency": "YEN",
      "extraField": {
        "Size": "9",
        "Color": "Red",
        "Material": "Denim"
      },
      "price": "249"
    },
    {
      "quantity": "18",
      "varientId": 12,
      "currency": "YEN",
      "extraField": {
        "Size": "8",
        "Color": "Green",
        "Material": "Rubber",
      },
      "price": "279"
    }
  ]
}

In addition to the data, an object is also provided:

var obj = {
        "Size": "10",
        "Color": "Red",
        "Material": "Denim"
      }

An attempt was made to search for the object within the dataset:

var index = null

for(var l = 0; l<data.variants.length; l++){
  if(data.variants[l].extraField === obj){
     index = l  
  } 
}

console.log(index)

Another alternative method using JSON.stringify was also tested:

JSON.stringify(data.variants[l].extraField) === JSON.stringify(obj)

The result obtained from console logging the index variable shows null instead of the expected value of 0, as the obj object matches with the first variant's extrafield.

Answer №1

The issue with your current method lies in attempting to directly compare two objects using the === operator, which is not suitable for object comparison. In JavaScript, objects are evaluated based on their reference and not their content. Therefore, even if two objects have identical key-value pairs, they will only be deemed equal if they are indeed the same entity in memory.

To ascertain the index of a matching object in an array, one can utilize the JSON.stringify() function to compare stringified versions of the objects. However, a more efficient solution exists by iteratively comparing individual properties within a loop. Below is a straightforward approach to solving this problem:

var data = {
  // Define your data object here...
};

var obj = {
  // Define your obj object here...
};

var index = null;

for (var i = 0; i < data.variants.length; i++) {
  var currentVariant = data.variants[i];
  var isEqual = true;

  for (var key in obj) {
    if (currentVariant.hasOwnProperty(key) && currentVariant[key] !== obj[key]) {
      isEqual = false;
      break;
    }
  }

  if (isEqual) {
    index = i;
    break;
  }
}

console.log(index);

This code correctly identifies the index of the initial object that matches the properties of the obj object within the data.variants array. It sequentially compares each variant's properties, exiting the loop upon discovering a match and assigning the found index to the index variable.

Answer №2

When it comes to comparing objects with ===, it won't work because they are different objects and you would be comparing references instead. Instead, a shallow comparison can be used by checking each property. However, the most efficient solution in this scenario is to compare using JSON.stringify, which simplifies the process. Running this code will display the number 0 in the console, indicating the index of the desired object.

var data = {
  "variants": [{
      "quantity": "20",
      "varientId": 8,
      "currency": "YEN",
      "extraField": {
        "Size": "10",
        "Color": "Red",
        "Material": "Denim"
      },
      "price": "199"
    },
    {
      "quantity": "15",
      "varientId": 10,
      "currency": "YEN",
      "extraField": {
        "Size": "9",
        "Color": "Red",
        "Material": "Denim"
      },
      "price": "249"
    },
    {
      "quantity": "18",
      "varientId": 12,
      "currency": "YEN",
      "extraField": {
        "Size": "8",
        "Color": "Green",
        "Material": "Rubber",
      },
      "price": "279"
    }
  ]
}

var obj = {
  "Size": "10",
  "Color": "Red",
  "Material": "Denim"
}

var index = null

for (var l = 0; l < data.variants.length; l++) {
  const isEqual = JSON.stringify(data.variants[l].extraField) === JSON.stringify(obj)
  if (isEqual) {
    index = l
  }
}

console.log(index)

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

Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one. You can view my implementation in this JS Bin ...

Strategies for restricting user input within a datalist

I have a project in which I am creating a webpage that displays a list of flights that can be filtered by destination, origin, price, and more. To achieve this, I have categorized each flight within a div element using its specific properties as classes. F ...

Having trouble connecting the HTML file with the JavaScript file

This is my unique HTML file <!DOCTYPE html> <html> <head> <script src="ll.js"></script> </head> <body> <link rel="stylesheet" href="home.css"> ...

I'm encountering an issue with my function in Vuejs where it is only going through one loop before breaking out. How can I

I'm attempting to validate all items in the cart and disable the sell button if the item is already in the cart (I have this implemented for other functionalities). It seems like my loop is only iterating once before stopping. Any suggestions on how I ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Tips for showcasing the outcome of an SQL query on an HTML page

I need assistance with displaying the output of an SQL query on my website. My server-side is using NodeJs and client-side is VueJs. After querying my database, I received the following result: [ { Time_Stamp: 2019-12-09T11:54:00.000Z, Time_Sta ...

Monitoring changes in the size of the parent element with an AngularJS directive

Issue I am facing a challenge with a directive that updates the size of an element based on the window size. The directive monitors changes in window dimensions and adjusts the element accordingly. MyApp.directive('resizeTest', ['$window&a ...

Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom ...

How to quickly mask an array in C# to exclude specific indexes, similar to Python's approach

My Data Situation: //The dataset I have includes columns (second index) with the same value in each row (first index) double[][] dataSet = new double[][] { new double[] {1, 2, 3, 4}, new double[] {5, 6, 7, 4}, new double[] {8, 9, 10, 4}, }; My Desi ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...

How can I dynamically assign ngModel in AngularJS?

I've created a directive with an isolate scope that maps a list of objects to inputs for modifying a specific property. However, I now aim to make this component more universal by allowing it to bind to deeply nested properties within each object. Fo ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain. To address this issue, I included a receptor.ts file in the /pages/api directory: import { NextApiRequest, Next ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Determine the position and quantity of elements in jQuery by comparing their IDs with the current page or element

Looking to retrieve the n (zero based) position of an element by matching the page and element ID... Let's use an example (Assume the current page ID is 488); <ul id="work-grid"> <li id="item-486" class="work-item"><!--/content--& ...

Adjusting element placement on collapsed navbar using Bootstrap

I've been developing a navbar for a webpage and have successfully aligned the data left and right with the Brand in the center. However, when the navbar collapses, the alignment shifts to Left (over) Brand (over) Right. I want the Brand to remain at t ...

How to extract a nested array in JSON within another array

I need help with deserializing a JSON file into an object. { "InputFileFolder": "D:\\MontlyTransactions\\", "TransactionGroups": [ { "Name": "Income", "FilterString": "Type=@0 and Amount>@1 and (Description.Cont ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

"Rails Ajax spinner functions properly in the development environment, but encounters issues in the

I am currently implementing this JavaScript code: verify_link.js ... a=$(this).parent(); a.html('<img src="assets/ajax-loader.gif">'); ... The image file is located in app/assets/images/ajax-loader.gif Everything works fine in de ...