Home > OS >  How to access object keys names in javascript
How to access object keys names in javascript

Time:05-09

console.log(answerKey);

for(singleKey in answerKey){
     
}

answerKey is my object. Can anybody please tell that how can I access object key names and values. Please see the screenshot (https://prnt.sc/nKTfE4GzoCMW)

CodePudding user response:

To access the keys and values separately, you can use Object.keys() and Object.values() methods separately.

const answerKey = {
  key1: 'answer1',
  key2: 'answer2',
  key3: 'answer3',
  key4: 'answer4',
  key5: 'answer5'
};

console.log(Object.keys(answerKey));

console.log(Object.values(answerKey));

If you want to access together, you can either iterate over the Object.keys() or you can also use the inbuilt Object.entries() method.

const answerKey = {
  key1: 'answer1',
  key2: 'answer2',
  key3: 'answer3',
  key4: 'answer4',
  key5: 'answer5'
};

console.log(Object.entries(answerKey));

Object.keys(answerKey).forEach(key => {
    console.log(key, answerKey[key]);
})

CodePudding user response:

I got it by using this

for(singleKey in answerKey){
     console.log(Object.keys(answerKey[singleKey])[0]); 
}

  • Related