0

How to get the name of the object which has blank value. In below case should get name 'end'.

   filterAry = [{name: 'start', value: '25/10/2021'},{name: 'end', value: ''}]

I tried below approach but not getting desired result

 const doEmptyAction = filterAry.every(o => o.value === '')

Please help how to achieve this.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
user1881845
  • 371
  • 2
  • 7
  • 16
  • 1
    Why are you using [Array.protoype.every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) which checks if every entry in the array passes the predicate! – phuzi Jul 25 '22 at 13:29
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Heretic Monkey Jul 27 '22 at 14:06

5 Answers5

3

Look at the documentation for every:

The every() method tests whether all elements in the array pass the test implemented by the provided function.

You know that not every element passes the test, so it isn't helpful here.

You need find or filter.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

You can use Array.prototype.find() method to find that object which has no value and then access name property on it

const obj = filterAry.find(el => !el.value);
obj.name // prints 'end'
Pratik Wadekar
  • 1,198
  • 8
  • 15
2

If you look at Array.every definition you will see that it's use case is different - it tells you whether every item in the array complies with some behavior (in your case if it's value is an empty string)

I think that Array.filter is what you are looking for in this case:

filterAry.filter(item =>item.value === '')

will return all of the items that has a value with an empty string.

If you just want to take the name from that use Array.map to take only the name from each of those items:

filterAry
  .filter(item =>item.value === '')
  .map(item => item.name)
OrenLevi
  • 91
  • 3
1

Using .every will return a boolean (true if all the elements on the array meet the condition).

To get all elements with emptyValues you can do:

const doEmptyAction = filterAry.filter(o => o.value === '')

which will give you a new array, containing only the matching values.

if you want just the first matching value, you can replace the filter with find.

McKean
  • 521
  • 6
  • 15
1

I agree with many answers in here that you should use either find() or filter(). But another option that you have is Array.prototype.some().

See this example:

filterAry = [{name: 'start', value: '25/10/2021'},{name: 'end', value: ''}];
const doEmptyAction = filterAry.some(o => Object.values(o).includes(''));
console.log(doEmptyAction);
Reza Saadati
  • 5,018
  • 4
  • 27
  • 64