Determine if a specific value is present in an array of objects using AngularJS

var arr = [ { id:1}, {id:2} ];
var obj = {id:1};
var result = arr.indexOf(obj.id) == -1;
console.log(result);

I am trying to determine if obj.id exists in the array arr[].
Please note: arr[] is an array of objects

Answer №1

Give this a shot...

    var array = [{ id:1}, {id:2}];
    var target={id:1};
    var idsArray = array.map(function(obj){
                               return obj.id
                          }); // create an array of all ids 
    var found = idsArray.indexOf(target.id) != -1 // check if target id is in array
    console.log(found);

Check out the Map and indexOf documentation for more info.

Answer №2

Here's a solution that should function correctly:

const items = [{ id: 1 }, { id: 2 }];
const query = { id: 1 };
console.log(items.findIndex(item => item.id === query.id));

The indexOf method is useful for indexed arrays but may not work as expected when dealing with arrays of objects.

Answer №3

Kindly make use of the code snippet below:

var arr = [ { id:1}, {id:2} ];
var obj={id:1}

function searchMatch(item) {
  return item.id === obj.id;
}

console.log(arr.findIndex(searchMatch));

Answer №4

An alternative approach is to utilize the .find method.

let a = [{
    id: 1
  }, {
    id: 2
  }],
  b = {
    id: 1
  },
  obj = a.find(function(itm) {
    return itm.id == b.id;
  });

console.log(obj)

Another useful function is .findIndex, which returns the index of an item in the array.

let a = [{
    id: 1
  }, {
    id: 2
  }],
  b = {
    id: 1
  },
  objIndex = a.findIndex(function(itm) {
    return itm.id == b.id;
  });

console.log(objIndex)

To retrieve all objects that meet a certain condition, you can employ the .filter function.

let a = [{
    id: 1
  }, {
    id: 2
  }],
  b = {
    id: 1
  },
  objArr =  a.filter(function(itm) {
      return itm.id == b.id;
  });

console.log(objArr)

Answer №5

In the Array.map() function, it compares the ID and its value, returning a Boolean value if the map is present, as highlighted by @Slava Utesinov.

var array = [{id: 1}, {id: 2}];
var obj = {id: 1};
if(array.map(item => item.id).indexOf(obj.id) != -1){
  console.log("Exists");
}else{
  console.log("Does not exist");
}

Answer №6

give this a shot

let animals = [ { name:"lion", sound: "roar" }, {name:"dog", sound: "bark"} ];

let chosenAnimal = {name: "lion"};

console.log(animals.find(animal => animal.name === chosenAnimal.name)) // returns matched record

let animals = [{ name: "elephant", size: "large" }];

let chosenAnimal = { name: "giraffe" };

console.log(animals.find(animal => animal.name === chosenAnimal.name)) // returns undefined

Answer №7

To verify, you can utilize the Array.map() method in JavaScript. This function will compare the id property and its corresponding value.

Here is a snippet of functional code:

var array = [{
  id: 1
}, {
  id: 2
}];
var obj = {
  id: 1
};

if (array.map(item => item.id).indexOf(obj.id) != -1) {
  console.log("Item exists");
} else {
  console.log("Item does not exist");
}

Answer №8

If you're working with AngularJS, utilizing the Filter feature can be helpful.

var array1 = [{id:1}, {id:2}];
var object1 = {id:1};

var isFound = false;
var filteredResult = $filter('filter')(array1, {id: object1.id}, true);

if (filteredResult.length > 0) {
    isFound = true;
}

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

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

What is the best way to dynamically link an Angular Material table with information pulled from the backend server

I am attempting to connect a mat-table with data from the backend API following this Angular Material Table Dynamic Columns without model. Below is the relevant content from the .ts file: technologyList = []; listTechnology = function () { ...

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...

Error: Unable to access attribute 'item_name' as it is not defined

I'm new to React.js and I'm attempting to build a todo app. The main feature is a text input field where users can add items to their list. When I run "npm start," the app works perfectly and displays the expected output on my designated port. Ho ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

Verifying the Angular API Connection with Laravel

I've recently started working on a project using both Laravel and Angular. I have configured a route as shown below: Route::group(array('prefix' => 'api'), function() { Route::resource('getdealsbymerchant/{merchant_id} ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

Mastering Vue.js: Leveraging v-model within a v-for loop and implementing watchers

After retrieving a list of debits and credits from a server using the fetch function, I store them in my Vue application: const myApp = Vue.createApp({ data(){ return{ debits:[], credits:[], //cut } }, me ...

Error: Unable to access the lexical declaration 'useStyles' before it has been initialized in the React Collapse Component. This issue occurred while trying to fetch data using axios in the Material-

I am facing an issue while trying to display data fetched from the backend (array with objects) and hide a portion of it under a collapsible button using Material-UI in React. The code works perfectly when all lines are written within a single component ca ...

How can you convert an epoch datetime value from a textbox into a human-readable 24-hour date format

I have an initial textbox that displays an epoch datetime stamp. Since this format is not easily readable by humans, I made it hidden and readonly. Now, I want to take the epoch value from the first textbox and convert it into a 24-hour human-readable da ...

Ajax external variable

I successfully uploaded a json file via Ajax using vanilla JS. { "list": [ {"name": "Executor", "date": "19.04.2017, 12:32:57"}, ... ] } Although I am able to change the "date" value for the current one using addEventListener, my challenge no ...

Incorporating object data and a value into an Angular $http.post request and retrieving them in an ASP .NET Web API

I am seeking a way to send multiple objects and a value from an Angular application to an ASP .NET Web API. Below is the snippet of my JavaScript code: var productStockArray = $scope.ProductStockArray; var challan = 20; $http.post(dataUrl + "StockProduc ...

Is there a way to convince Python to interpret data as a multi-dimensional list instead of a string when converting from HTML?

Currently, I am working on formatting table data in HTML and then sending it to Python using the script below: var html_table_data = ""; var bRowStarted = true; var count1 = 1 $('#woTable tbody>tr').each(function () { if (count1 != 1) { ...

Mapping dynamic objects inside a repeat loop in AngularJS ui-select

Here is my ui-select directive code that is working perfectly fine. Within a repeat loop, I need to dynamically set the property of the CODE object (which is ID) to something like code[fwValueProperty]. Since it is not using ng-repeat, I cannot use it in ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

jQuery "slide" animation without using <br>

I've been working on a website that incorporates the jQuery "Slide" effect. I have implemented this effect multiple times, using it on 3 different div tags. Each line consists of one "Dynamic" div tag (the moving one) and one "Static" div tag (the tri ...

The getStaticProps function in Next.js does not pass any data back to the pages

After setting up my hosted database, I encountered an issue with fetching data from it. Despite confirming that the database is running smoothly through the Swagger app, no data appears when called via API form. import React from 'react'; export ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...