将动态值与对象中的 object.keys 进行匹配

1 javascript ecmascript-6

如果它是数组我可以这样做 myArr[0] 来获取第一个值,但如果它是一个对象怎么办?说我的对象是这样的

{a: 'some value', b: 'another thing'}

如何匹配第一个对象?

['a', 'b'].map(o => //match object return true) 我期望得到,[true, true]因为数组与['a','b']对象的键值匹配。

Cer*_*nce 6

使用mapin

const obj = {a: 'some value', b: 'another thing'};
console.log(['a', 'foo', 'b'].map(key => key in obj));
Run Code Online (Sandbox Code Playgroud)

或者,如果该属性可能存在于原型链中并且您不想包含继承的属性,请改用Object.keys

const obj = {
  a: 'some value',
  b: 'another thing'
};
const keys = Object.keys(obj);
console.log(['a', 'foo', 'b'].map(key => keys.includes(key)));
Run Code Online (Sandbox Code Playgroud)