这是我的:
fields = [ { apple: 'red' }, { banana: 'yellow' } ]
fields.forEach(field => {
// trying to get the key here
if (Object.keys(field)[0] === 'apple')
console.log('works!')
})
我想问一下有没有简单的方法可以让我拿到 key ?我觉得我使用
让它变得太复杂了Object.key(field)[0]
添加:我只是想从这个对象数组中获取每个键并与字符串进行比较。
最佳答案
您应该使用includes
来检查apple
是否在数组Object.keys(field)
中
let fields = [{ apple: 'red'}, { banana: 'yellow'}];
fields.forEach(field => {
// trying to get the key here
if (Object.keys(field).includes('apple'))
console.log('works!')
});
关于javascript - 从对象javascript获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876740/