Reputation: 2166
Using Lodash I am trying to find if a value exists in the collection or not.
If exists I want to return true
else false
.
const d = [{
"country": "India",
"_id": ObjectId("5ad47b639048dd2367e95d48"),
"cities": []
}, {
"country": "Spain",
"_id": ObjectId("5ad47b639048dd2367e95d49"),
"cities": []
}];
Snippet Code
Countries = ['India', 'Spain']
if (_.has(d, Countries)) {
console.log(true);
} else {
console.log(false);
}
But it Always returns False. It's not recommended for me to use lodash
can anyone suggests a better way if possible.
Upvotes: 0
Views: 4720
Reputation: 407
Inspired by @Christian Bartram
var cities = [
{city: "Beijing",bOn:false},
{city: "Shanghai",bOn:false},
{city: "Chongqing",bOn:false},
{city: "Guangzhou",bOn:false}, {city: "Guangzhou",bOn:true},
{city: "Xi'an",bOn:false}
];
//Find duplicate element values in the array
_(cities).groupBy(x => x.city).pickBy(x => x.length > 1).keys().value()
Return
['Guangzhou']
//Find duplicate objects in an array
_.filter(_(cities).groupBy(x => x.city).value(),x => x.length > 1)
Return
[[{"city":"Guangzhou","bOn":false},{"city":"Guangzhou","bOn":true}]]
Upvotes: 0
Reputation: 10262
You could use array.some()
and array.includes()
for checking duplicate entries in array.
DEMO
const d = [{
"country": "India",
"_id": "5ad47b639048dd2367e95d48",
"cities": []
}, {
"country": "Spain",
"_id": "5ad47b639048dd2367e95d49",
"cities": []
}];
const Countries = ['India', 'Spain'];
console.log(d.some(({country}) => Countries.includes(country)))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 411
You can also do this without Lodash using Javascripts built in filter
function
d.filter(item => item.country === "Spain"); //Would return an array of objects where the country's name property is Spain!
if we wanted to make this a boolean we could declare it as a variable and assert its length is greater than 0 like so:
let isSpanishCountry = d.filter(item => item.country === "Spain").length > 0; // console.log(isSpanishCountry) => true
Upvotes: 0
Reputation: 19607
You can use the combination of some
and includes
methods. It will return true
, if any item in items
contains country from countries
array.
const items = [
{
"country": "India",
"_id": 'ObjectId("5ad47b639048dd2367e95d48")',
"cities": []
},
{
"country": "Spain",
"_id": 'ObjectId("5ad47b639048dd2367e95d49")',
"cities": []
}
];
const countries = ['India', 'Spain'];
const includes = _.some(items, item => _.includes(countries , item.country));
console.log(includes);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
Upvotes: 4