How to Retrieve the Order Number of an Object in an Array using JavaScript ES6

Curious about JavaScript ES6 and needing assistance! I have a simple question - how can I determine the order number of an object in an array?

[
  { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 11, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 67, "image": "http://localhost:8000/media/users/1/2_27.jpg"}
]

Given params.id: 11, I would like to output order_object = 2

Answer №1

If you're searching for the findIndex method

var order_object = arr.findIndex( s => s.pk == 11 ) + 1;

Check out this demonstration:

var arr  = [
  { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 11, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 67, "image": "http://localhost:8000/media/users/1/2_27.jpg"}
];

var order_object = arr.findIndex( s => s.pk == 11 ) + 1;

console.log( order_object );

Answer №2

If you need to locate the initial index of a predicate match, consider utilizing the [].findIndex() method in JavaScript.

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

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

"Positioning a div around a Bootstrap form-inline: A step-by-step guide

When using Bootstrap 3 "form-inline" within a <div>, I noticed that the div seems to be nested within the form-inline. This is how my code looks: HTML <div class="wrapper"> <div class="form-inline"> <div ...

Dynamically load npm modules in Webpack using variables for the require statement

Is there a way to dynamically require an NPM module using a variable? Below is the sample code I've been trying, everything seems to be working fine except for importing NPM modules dynamically. const firstModule = 'my-npm-module'; const s ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...

What is the best way to retrieve a jobID from Kue?

I am currently working with Express and I'm facing a challenge in creating a job whenever someone posts to my route. My goal is to have the response include the job.id, but the job id is only generated within the callback of my queue.createFunction. I ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Implementing watch functionality with array in Vuejs for bidirectional communication between parent and child components

Here is a simplified version of a parent component I created: // parent component <template> <layout v-for="(value, idx) in array" :pickUpLength="array.length" :idx="idx" :key="idx" > <button @click="addArray">a ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

step-by-step guide on transferring the text content of an HTML paragraph element to another HTML paragraph element through JavaScript in ASP.NET

I'm looking for help with passing the text value from one HTML paragraph element to another when a JavaScript function is called. The function loads a div element with an enlarged image and a paragraph content. Below is the code I am using: JavaScrip ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

Issue with manipulating currency conversion data

Currently, I am embarking on a project to develop a currency conversion application resembling the one found on Google's platform. The main hurdle I am facing lies in restructuring the data obtained from fixer.io to achieve a similar conversion method ...

Enhancing the efficiency of a JavaScript smooth scrolling feature for numerous listed items

I have been experimenting with recreating the recent Apple Mac retrospective using only CSS and JavaScript to create a small timeline of projects. While I have successfully implemented the layout for the full-screen hero and the expand-on-hover effect, I a ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

receiving onPaste or onChange events within a component that generates input fields

My goal is to achieve the following functionality: <MyTextInput onChange={console.log("Change")} /> This particular component serves as a container for <input type="text" /> without triggering any action when text is typed (the purpose of usi ...

Issue with z-index causing the image to not display when navigating through an image gallery with previous and next buttons using

$(document).ready(function(){ $(".divs div.panel").each(function(e) { if (e > 2) $(this).hide(); console.log(e); }); $("#next").click(function(){ if ($ ...

Efficiently update a multi-step form using Ajax and jQuery by adding new content without needing to reload the

Is it possible to create a multistep form on a single page without reloading the div with content from a PHP file, but instead appending it below? Here is my current progress: $(document).on('submit', '#reg-form', function(){ var ln = ...

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

Troubleshooting compatibility issues between ExpressJS's res.render and AngularJS

I'm relatively new to Node.js, Express, and AngularJS. I'm currently working on a basic Sign-in feature that will redirect to another page upon successful sign-in. While I know I can use window.location for the redirection, I'm trying to uti ...