Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash to find if object property exists in array

Tags:

I have an array of objects like this:

[ {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
]

I want to insert another element, also named apple, however, because I don't want duplicates in there, how can I use lodash to see if there already is an object in the array with that same name?

like image 303
reectrix Avatar asked Oct 19 '16 17:10

reectrix


2 Answers

You can use Lodash _.find() like this.

var data = [ {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
]

if(!_.find(data, {name: 'apple'})) {
  data.push({name: 'apple2'});
}
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Reference documentation: https://lodash.com/docs/4.17.14#find

like image 151
Nenad Vracar Avatar answered Oct 23 '22 03:10

Nenad Vracar


This is Form

_.has(object, path)

Example:

const countries = { country: { name: 'Venezuela' } }
const isExist = _.has(countries, 'country.name')
// isExist = true

For more information Document Lodash

like image 42
Alex Quintero Avatar answered Oct 23 '22 03:10

Alex Quintero