动态检查数组的对象是否具有一个或多个键?

时间:2018-06-28 11:34:32

标签: javascript

是否可以检测数组中的对象是否具有键,甚至我都不知道对象的键?

示例:

var a = [{}]
var b = [{a:1}] /* or [{a:1},{b:1}] or [{b:1}] */

if(a){ return false }
else if(b){ return true }

如果我使用了.length,结果将是1

  

注意:密钥是dynamically

3 个答案:

答案 0 :(得分:2)

您可以使用Object.keys来获取密钥(以数组形式)。使用length获取键数

var a = [{}]
var b = [{a: 1}] 

if (Object.keys(a[0]).length) console.log('a[0] has keys');
else console.log('a[0] has no keys');

if (Object.keys(b[0]).length) console.log('b[0] has keys');
else console.log('b[0] has no keys');


如果对象上的某些对象具有键,而有些对象则没有,则可以使用some

let hasKeys = a => {
  return a.some( o => Object.keys(o).length );
}
	
let a = [{}];  //false
let b = [{a: 1}];  //true
let c = [{},{}]; //false
let d = [{a:1},{b:1}]; //true
let e = [{},{b:1}]; //true
	
console.log( 'a' , hasKeys( a ) );
console.log( 'b' , hasKeys( b ) );
console.log( 'c' , hasKeys( c ) );
console.log( 'd' , hasKeys( d ) );
console.log( 'e' , hasKeys( e ) );

答案 1 :(得分:1)

这就是我要这样做的方式,因为我想控制所涉及的键的数量。否则,如果只需要知道对象中是否有任何键,则只需使用.some()就可以了。

const a = [{}];
const b = [{foo:1}];
const c = [{bar:1, foz: 1, baz: 1}];
const d = [{beep:1}, {boop:2}];

const getAmountOfKeys = (arr) => {
  return arr.map((item) => Object.keys(item).length).reduce((a, b) => a + b);
}

console.log(`a has ${getAmountOfKeys(a)} keys`);
console.log(`b has ${getAmountOfKeys(b)} keys`);
console.log(`c has ${getAmountOfKeys(c)} keys`);
console.log(`d has ${getAmountOfKeys(d)} keys`);

答案 2 :(得分:0)

您可以使用Array.prototype.someObject.keys

const anyObjectHasKey = (key,array) => 
  array.some(o=>(o&&Object.keys(o).some(k=>k===key)))

const a = [{}];
const b = [{a: 1}];
console.log("a in a",anyObjectHasKey("a",a));
console.log("a in b",anyObjectHasKey("a",b));