简体   繁体   中英

JavaScript shortcut for checking a particular key-value inside array of objects

I am angular developer, don't know much about JavaScript shorthand methods.

I came across a situation where I need to loop through using for loop in JavaScript.

Assume that I am having an array of Objects like

var arr = [{name:'abc', val:1}, {name:'xyz', val:2}, ....];

Given a string 'xyz', Is there any JavaScript/Angular shorthand without using for loop to return true if my array of objects hold name as 'xyz' value.

I am looking for a shorthand expression , something like indexOf function.

Any help is greatly appreciated.

You can use

if (arr.filter(function(x) { return x.name === 'xyz'; }).length > 0) { ... }

in pre-ES6.

This is a more cumbersome version and of course you could extract your function to have a more readable/flexible version as such:

function equaling(attr, value) { 
  return function(obj) {
    return (obj || {})[attr] === value; 
  };
}

if (arr.filter(equaling('name', 'xyz')).length > 0) { ... }

You could also use

if (arr.some(({ name }) => name === 'xyz')) { ... }

with ES6 / ES2015. This basically takes advantage of the most recent language features and is readable, expressive and maintainable without the need to create own functions.

The features mentioned are:

  • (value) => expression : This is an arrow function (shorthand) equivalent of defining function literals and the result is close to the function definition in ES5 ( function(value) { return expression; } ) - the difference is that this in the arrow function variant is different than this in the function variant.
  • ({ name }) => ... : This is an object spread expression that allows you to easily de-structure any object into its components (or parts of its components) based on attribute names.

No quick shorthand, the shortest and i think quickest solution would be to use Array.some

var hasName = arr.some(o => o.name === "xyz")

which will be interrupted as soon as one matching element is encountered and would give you either true or false

You can loop through with the angular forEach function to search for it.

var matchingIndex = -1;
angular.forEach($scope.data, function(item, itemIndex) {
   if(item.name === "xyz"){
      matchingIndex = itemIndex;
   }
});
console.log(matchingIndex);

If you cannot use the array "some" function then you should simply construct a basic for loop and test therein.

Avoid using array functions such as "forEach" or "filter" as they will require you to examine the entire array thus guaranteeing worst-case performance every time, even if the item of interest is at the start of your array. Short-circuiting "forEach" of "filter" will require you to do something ugly such as wrapping the function invocation in a try-catch block and then throwing once a match is found (dont do that).

So, if you can't use the "some" function then accept a basic for loop and break as soon as you find a match.

Another solution is to use array.findIndex . You can create function that checks existence of the element with the specified name:

const findByName = (name) => arr.findIndex(elem => elem.name === 'xyz') > -1;

And then use it:

findByName('xyz')  // true
findByName('wrongName')  // false

Check it: https://jsfiddle.net/63ayto1w/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM