查找Javascript数组中是否存在元素

Red*_*ddy 2 javascript arrays ecmascript-6

我试图找到一个元素是否存在于Array名称中.想不通,如何实现同样的目标

let string = [{"plugin":[""]}, {"test": "123"}]
console.log(string);
console.log(string instanceof Array); //true
console.log("plugin" in string); //false
Run Code Online (Sandbox Code Playgroud)

Tus*_*har 7

plugin 没有直接在数组中定义,它是在数组中的对象内定义的.

使用它Array#find来检查数组中的任何元素是否包含给定属性.

array.find(o => o.hasOwnProperty('plugin'))
Run Code Online (Sandbox Code Playgroud)

使用hasOwnProperty检查对象是有属性.

let array = [{"plugin":[""]}, {"test": "123"}];
let res = array.find(o => o.hasOwnProperty('plugin'));

console.log(res);
Run Code Online (Sandbox Code Playgroud)

作为选项,您也可以使用Array#filter.

array.filter(o => o.hasOwnProperty('plugin')).length > 0;
Run Code Online (Sandbox Code Playgroud)

let array = [{"plugin":[""]}, {"test": "123"}];
let containsPlugin = array.filter(o => o.hasOwnProperty('plugin')).length > 0;

console.log(containsPlugin);
Run Code Online (Sandbox Code Playgroud)