如果'monkey'没有退出数组,写一个函数返回值true。
const entities = [
{
id: 1,
name: 'cat',
},
{
id: 2,
name: 'dog',
},
{
id: 1,
name: 'pig',
},
];
const selection = 'monkey';
答案 0 :(得分:2)
<强> ES6 强>
entities.some((entity) => entity.name === selection);
<强> Lodash 强>
_.some(entities, ['name', selection]);
答案 1 :(得分:0)
这是一段示例代码。在函数中添加以下代码片段,调用它。它可以提供您想要的输出。
for(var i=0;i<entities.length;i++){
if(entities[i].name == 'monkey')
return true;
else
continue;
}
return false;
答案 2 :(得分:0)
考虑到你的数组将包含你提到的对象,你可以做这样的事情
private function _inArray(arr, value, key = "name"): boolean {
let found: boolean = false;
arr.some((obj) => {
return (found = obj[key] == value);
});
return found;
}
...
...
myFunc() {
const entities = [
{
id: 1,
name: 'cat',
},
{
id: 2,
name: 'dog',
},
{
id: 1,
name: 'pig',
},
];
const selection = 'monkey';
this._inArray(entities, selection);
//Since you need it in lodash here it is
_.some(entities, ['name', 'monkey']);
}
答案 3 :(得分:0)
这是一个es2015解决方案。
const entities = [
{
id: 1,
name: 'cat',
},
{
id: 2,
name: 'dog',
},
{
id: 1,
name: 'pig',
},
];
function doesntContainMonkey() {
return !entities.find(x=>x.name === 'monkey');
}
doesntContainMonkey(); //true
答案 4 :(得分:0)
function searchInArray(s, a, prop) {
for(var i = 0; i < a.length; i++) {
if(a[i][prop] === s) return i;
}
return false;
}
用法:
searchInArray("monkey", entities, "name")
答案 5 :(得分:0)
试试这种方式
var index=entities.findIndex(x=>x.name==selection);
if(index == -1)//-1 means the searched item is not present.
return true;
else
return false;