从对象javascript获取密钥

时间:2019-02-26 00:21:52

标签: javascript ecmascript-6

这里是我所拥有的:

Route::get('/', function() {
    return redirect()->route('frontend');
});

// Route everything else to Vue
Route::get('panel/{any?}', function () {
   return file_get_contents(public_path().'/panel/index.html');
})->where('any', '.*')->name('frontend');

我想问问我是否有一种简单的方法来获取密钥?我觉得

使我变得太复杂了
fields = [ { apple: 'red' }, { banana: 'yellow' } ]

fields.forEach(field => {
    // trying to get the key here
    if (Object.keys(field)[0] === 'apple')
        console.log('works!')
})

add:我只是想从该对象数组中获取每个键,并与一个字符串进行比较。

2 个答案:

答案 0 :(得分:1)

您应该使用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!')
});

答案 1 :(得分:1)

您可以简单地使用destructuring assignment

let fields = [ { apple: 'red' }, { banana: 'yellow' } ]

fields.forEach( e => {
    let [key] = Object.keys(e)

    if (key === 'apple')
      console.log('works!')
})