使用Lodash从Collection中查找重复值

时间:2018-04-16 11:56:32

标签: javascript arrays json lodash

使用Lodash我试图找出集合中是否存在值。

如果存在,我想返回true其他false

 const d = [{
     "country": "India",
     "_id": ObjectId("5ad47b639048dd2367e95d48"),
     "cities": []
 }, {
     "country": "Spain",
     "_id": ObjectId("5ad47b639048dd2367e95d49"),
     "cities": []
 }];

代码段

Countries = ['India', 'Spain']
if (_.has(d, Countries)) {
    console.log(true);
} else {
    console.log(false);
}

但它总是返回False。我不推荐使用lodash,如果可能的话,任何人都可以建议更好的方法。

3 个答案:

答案 0 :(得分:4)

您可以使用someincludes方法的组合。如果true中的任何项目包含items数组中的国家/地区,则会返回countries



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/lodash@4.17.5/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

ES6

您可以使用array.some()array.includes()来检查数组中的重复条目。

<强>样本

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; }

答案 2 :(得分:0)

您也可以使用filter函数

中内置的Javascripts在没有Lodash的情况下执行此操作
d.filter(item => item.country === "Spain"); //Would return an array of objects where the country's name property is Spain!

如果我们想让它成为一个布尔值,我们可以将它声明为一个变量,并断言它的长度大于0,如下所示:

let isSpanishCountry = d.filter(item => item.country === "Spain").length > 0; // console.log(isSpanishCountry) => true