Validating Presence of a Value in an Array Object Using AngularJS

var SelectedOptionId = 957;

$scope.array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}]

Is there a method to verify the existence of a value within an array of objects like this using Angular and underscore?

I've attempted the following approaches:

if ($scope.array.indexOf(SelectedOptionId) === -1) {console.log('already exists')}

as well as

console.log($scope.array.hasOwnProperty(SelectedOptionId)); //returns false

and

console.log(_.has($scope.array, SelectedOptionId)); //returns false 

Answer №1

If you want to validate if a certain option exists in an array, you can utilize the Array#some method along with the in operator.

exists = $scope.array.some(function (o) {
    return SelectedOptionId in o;
});

Answer №2

Verify this

function validateInput (input) {
   return $scope.list.some(function (item) { 
    return item === input;
  }
}

var result=validateInput("your input")

Answer №3

Give this a shot:

if($scope.array[SelectedOptionId] || _.includes(_.values($scope.array, SelectedOptionId))) { }

This code handles both key and value scenarios.

Answer №4

const chosenId = "1212";
let newArr = [{"1212":"12"},{"1213":"15"},{"1214":"18"},{"1215":"14"},{"1216":"17"}];

let result = newArr.filter(function(item){
    return Object.keys(item)[0] === chosenId; 
  });

console.log(result);

Answer №5

console.log(_.find($scope.array, function(obj) { return _.has(obj, "957"); }));

Implementing underscore functions

Answer №6

If you need to filter an array based on a specific condition, you can utilize the filter method. The code snippet below demonstrates how you can achieve this by returning an array with items that meet the criteria:

var data = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var selectedKey = 957;

var filteredArray = data.filter(
  function(item) {return item[selectedKey]}
)

console.log(filteredArray);

When you input this data, the output will be:

[ { '957': '1269' }, { '957': '1269' } ]

Answer №7

If you want to determine if a key exists in an object within an array, you can utilize either the in operator or the hasOwnProperty function.

Your previous attempt at using the hasOwnProperty function may not have worked because you were checking it directly on the array itself instead of on the items within the array.

Take a look at the following code snippet.

angular
  .module('demo', [])
  .controller('HomeController', DefaultController);

function DefaultController() {
  var vm = this;
  vm.items = [{
    "957": "1269"
  }, {
    "958": "1265"
  }, {
    "956": "1259"
  }, {
    "957": "1269"
  }, {
    "947": "1267"
  }];

  var key = '957';
  var isExists = keyExists(key, vm.items);
  console.log('is ' + key + ' exists: ' + isExists);

  function keyExists(key, items) {
    for (var i = 0; i < items.length; i++) {
      // if (key in items[i]) {
      if (items[i].hasOwnProperty(key)) {
        return true;
      }
    }

    return false;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="HomeController as home">
    {{home.items | json}}
  </div>
</div>

Answer №8

Various methods to achieve this :

  1. Utilizing the Object's hasOwnProperty() method.

Example :

var SelectedOptionId = 957;

var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];

function checkOption(key) {
  for(var i in arrayObj) {
    if(arrayObj[i].hasOwnProperty(key) == true) {
      return key+" exists.";
    } else {
      return key+" Not exists.";
    }
  } 
};

console.log(checkOption(SelectedOptionId)); // 957 exists.

  1. using the Array's filter() method.

Example :

var SelectedOptionId = 957;

var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];

var result = arrayObj.filter(function(elem) {
  return elem[SelectedOptionId]
});

if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}

  1. using the Array's some() method as recommended by Nina Scholz.

Example :

var SelectedOptionId = 957;

var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];

var result = arrayObj.some(function (o) {
    return SelectedOptionId in o;
});

if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}

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

What causes the toggle effect in my jQuery onclick function to alternate between on and off when the initialization is repeated multiple times?

I am facing an issue with my website where icons/buttons trigger a menu when clicked. I need to load more data by adding more buttons, so I tried re-initializing the existing buttons using a jQuery onclick function whenever the number of buttons changes. ...

Removing an element from an array of objects using React

I am currently fetching data from a JSON file and using the map method to display it while storing it in a state. The goal is to delete an item when the delete button is clicked, so I am utilizing the filter method for this. However, I encountered an error ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Exploring the Versatility of the IN Operator in Jquery and Javascript

RatecardIDs=[2, 22, 23, 25]; if (parseInt(cellValue) in (RatecardIDs)) { } Is it possible to use the In operator in an if condition? This code first executes the code in the if block, but then it goes on to the else block. ...

Using Vue to implement a "v-model" on a custom component that incorporates the ace-editor

Snippet CustomEditor.vue: <template> <div class="custom-container"> <div class="custom-editor" ref="editor"></div> </div> </template> <script> import ace from 'ace-builds' import 'ace- ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Prevent JavaScript from being entered into the form

I'm currently developing an "HTML editor" for one of my webpages. Right now, I want to ensure that the editor only allows input of HTML and CSS elements without any Javascript (or Jquery). I've been attempting to prevent the use of <script> ...

The transfer of variables from AJAX to PHP is not working

My attempt to pass input from JavaScript to PHP using AJAX is not successful. I have included my JS and PHP code below: <!DOCTYPE html> <html> <head> <style> div{border:solid;} div{background-color:blue;} </style> </head&g ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

Successful jQuery Ajax request made without the need for JSON parsing

I find it strange that my experience with jQuery's ajax function is completely different from what I'm used to. Below is the javascript code in question: $.ajax({ url: "/myService.svc/DoAction", type: "GET", dataType: "json", su ...

Would you suggest using angularjs for authentication in large-scale applications?

As I continue to learn and utilize the AngularJS framework, I have noticed that while some of its features are impressive, some key aspects make it challenging for authentication-based applications. For example, let's consider a scenario where a webs ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...

Received a String instead of an Object while attempting to parse JSON data

Currently, my goal is to parse a JSON string using jQuery var parsedData = $.parseJSON('{"graph_info": "{}"}'); I assumed that typeof(parsedData.graph_data) would be an Object but surprisingly it is returning as a string. Can someone guide me o ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

Redux actions do not cooperate with functions, preferring to be implemented inline instead

I am a beginner in Redux and JavaScript and just came across this issue, When I use the line dispatch({type: 'REQUEST_START'}); it works fine, but when I write it like this: dispatch(requestStart); No actions are being fired! Any suggestions ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...