How to loop, capturing the keys and values of an object

Asked

Viewed 177 times

0

I would like to loop an object in order to capture the key and the corresponding value.

For example:

const obj = {
  'Chave 1': 'Valor 1',
  'Chave 2': 'Valor 2',
  'Chave N': 'Valor N'
};

I’d like to return something like this:

Chave 1 => Valor 1
Chave 2 => Valor 2
Chave N => Valor N

1 answer

1


To display the two key and value can do so

var obj = {
  'Name' : 'String 1',
  'Age' : 'String 2',
  'Key N': 'String N'
  }
  
  Object.keys(obj).forEach(function(item){
        console.log(item +' => '+ obj[item]);
    })

  • Actually I want to return the key too. Your answer only causes the value corresponding to the key Name is returned. I want to return the value and key.

  • @lffg I had understood otherwise, I made the correction, I hope, if that’s what you need.

  • Thank you, that’s right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.