Tips for finding the position of a specific object within an array of objects using JavaScript when it is an exact match

I am working with an array of objects and need to find the index of a specific object within the array when there is a match.

Here is an example of my current array:

let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
 .....
];

Previously, I was using indexOf to achieve this, but now it is not returning the correct index, instead giving -1.

let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = x.indexOf(find); // should return 1.

The entire object needs to be matched in order to retrieve the correct index. Do you have any suggestions on how I can accomplish this? Should I consider using some()? Your guidance would be greatly appreciated.

Thank you

Answer №1

Instead of using indexOf, you can opt for .find since two objects are never equal (as they point to different memory references), which seems to be the argument you are passing.

let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}}
];

let found = x.find(function(item) {
  // The condition can be implemented here
  return item.info.id === 564;
});

console.log(found);

To retrieve the index, consider using .findIndex method instead.

let x = [
    {name: "emily", info: { id: 123, gender: "female", age: 25}},
    {name: "maggie", info: { id: 234, gender: "female", age: 22}},
    {name: "kristy", info: { id: 564, gender: "female", age: 26}}
];

let foundIndex = x.findIndex(function(item) {
  // The condition can be implemented here
  return item.info.id === 564;
});

console.log(foundIndex);

Answer №2

To compare objects in JavaScript, traditional equality cannot be used. Instead, the ES6 findIndex method can be employed to compare each object's properties with desired values. An example is provided below:

let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}}
];
let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = x.findIndex(element => element.info.id === find.info.id); // index === 1

In your specific scenario, the id value appears to be a suitable identifier for an object; additional equality checks can be added if more properties need to be compared, using the && operator (e.g., element.name === find.name).

Answer №3

Living in the world of _.lodash makes this process seamless, as lodash excels at handling nested objects by going deep into them:

let data = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, age: 22, gender: "female"}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
];

let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = _.findIndex(data, (i) => _.isEqual(i, find))

console.log(index)  // 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

A more brute force method that is not efficient and fails if property order differs.

let data = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
];

var objectJSONs = data.map((i) => JSON.stringify(i))

let myJSON = JSON.stringify({name: "maggie", info: { id: 234, gender: "female", age: 22}});
let index = objectJSONs.indexOf(myJSON)

console.log(index) // 1

Answer №4

To compare objects, you can utilize the underscore _.isEqual function and implement a looping mechanism such as some() to iterate through the array.

let foundIndex = -1;
let isFound = array.some((element, index) => {
                    if(_.isEqual(element, targetObject){
                        foundIndex = index;
                        return true;
                    }
                    return false;
                  }
 //console.log(foundIndex);

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

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

Angular: The property '**' is not found on the type 'Object'

Not too long ago, I embarked on a new Angular project where my setup involves Angular (the front-end) communicating with a node.js server (the back-end), which in turn might make requests to an api server or a mongo database when necessary. The tricky par ...

Jasmine examination fails to progress to the subsequent segment of the promise

I want to test a specific function: function initializeView() { var deferred = $q.defer(); if(this.momentArray) { core.listMoments(constants.BEST_MOMENT_PREFIX, '').then(function(moments) { //Ommit ...

Not every time you call the AngularJS run method does it actually execute

Working on a simple Angular app, I wanted to implement a user login check and redirection. However, I encountered an issue where accessing the home page from the form site resulted in inconsistent behavior - sometimes redirecting and other times showing ...

Error always appears when using addMethod in jQuery validator

$.validator.addMethod("validateEmail", function() { $.ajax({ type: "POST", url: "/user/check_email", data: { email: $( "#email" ).val() }, success: function(data) { console.log(dat ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

A common error known as a segmentation fault occurs when attempting to access an array within a Fortran

My fortran program is experiencing issues with a subroutine causing a segmentation fault. The fault occurs after executing line 1434 and printing the message: i: 115 256 2 Segmentation fault (core dumped) The program has pa ...

Awaiting a response from the http.get() function

Currently, I am in the process of creating a login feature using Angular and Ionic 2. This feature aims to verify if the user is registered in the database through a PHP server and return a user ID. However, I have encountered an issue with the asynchronou ...

Guide to setting up CKeditor

I am struggling with the installation of CKEditor. After downloading the editor from the website, I inserted the code below between the head tags of my webpage: <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script typ ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

Converting an Observable Array into a nested JSON structure

Having difficulty storing an array of information properly as JSON. A visual representation of the issue can be seen in this fiddle. Input a set of tags and check the console for output. Additional detail: An input captures a comma-separated list of tag ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Having issues with JavaScript function returning value from Ajax request

My AJAX request function is functioning well - returning 1 for success and 2 for failure. However, I am facing an issue when trying to perform actions outside of this function based on the return value. Instead of getting either 1 or 2, I always receive "u ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...

Difficulty in decoding intricate JSON response using JQuery (or simply JavaScript)

Consider the function below, which retrieves JSON data from a Solr instance: var url = "http://myserver:8080/solr/select?indent=on&version=2.2&q=(title:*Hollis* OR sub_title:*Hollis*+OR+creator:*Hollis*+OR+publisher:*Hollis*+OR+format:*Hollis*++OR ...

Automated Star/Stop feature with a convenient Save button (the Start/Stop format will display as mm/dd/yyyy hh:mm:ss)

I'm having an issue with the date format in my code. Currently, it displays as Mon Mar 13 2017 19:02:50 GMT-0400 (Eastern Daylight Time), but I need it to be in the format mm/dd/yyyy 00:00:00 am/pm. My challenge is to capture the current date and tim ...