user1234
user1234

Reputation: 3159

How to get a key/value pair for an object

This question may sound very stupid, but I want to get a key/value pair for my object:

var a = {"e":1,"d":3,"f":4}

I tried with Object.keys(a) // returns ["e", "d", "f"]

this does not get me the values associated with the keys, how can I get both to be able to display in a page.

html:

<div>
  <img src={value}/> //here i want value 1 to be displayed
{key} //with "e"
</div>

how do I do it? Thanks!!

Upvotes: 3

Views: 3578

Answers (4)

Thanh Lam
Thanh Lam

Reputation: 696

If you want to get a single value:

Just use: *a.e* or *a[e]* return 1 

eg. <img src={a.e} />

If you want to iterate an Object to get value there several ways:

var a = {"e":1,"d":3,"f":4}

Method 1: Using for:

for ( var x in a) {
    console.log('v:',a[x]);
}

Method 2: Using map:

Object.keys(a).map( (k) => {console.log('k',a[k])} );

Method 3: Using foreach:

Object.keys(a).forEach(function(key,index) {
        console.log('a[key]',a[key]);
      });

Upvotes: 2

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21766

Here you go. To get key/value pair from an object, do it like below using pure JavaScript way Object.entries():

var a = {"e":1,"d":3,"f":4}

for (const [key, value] of Object.entries(a)) {
  console.log(`${key} ${value}`);
}

Upvotes: 4

Giacomo Ciampoli
Giacomo Ciampoli

Reputation: 821

var a = {"e":1,"d":3,"f":4}
let container = document.querySelector('.container')

Object.entries(a).forEach(entry =>{
	let div = document.createElement('div')
  let img = document.createElement('img')
  img.src = entry[1]
  div.textContent = entry[0]
  div.appendChild(img)
  
  container.appendChild(div)
})
<div class="container">
  
</div>

Upvotes: 1

edh4131
edh4131

Reputation: 60

One way you can do it is like this:

var a = {"e":1,"d":3,"f":4}

 for(var key in a){
  alert(key + ' : ' + a[key])
 }

If you need to iterate over each pair that is. However for in loops are kind of janky in javascript and you should read a bit about going that route if you decide to.

https://jsfiddle.net/edh4131/hd9p7cxq/

Upvotes: 1

Related Questions