3

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!!

user1234
  • 3,000
  • 4
  • 50
  • 102
  • 1
    `Object.values` for just the values or maybe use `Object.entries` to get the key/value pairs. – CRice Mar 27 '18 at 23:55
  • 1
    `Object.entries(a).forEach(([key, value]) => do stuff)` – Ele Mar 27 '18 at 23:55
  • Thanks all for your help and answers, it helped me a lot!!!! – user1234 Mar 28 '18 at 00:52
  • if you know the key, just use the key to access the value... object[key] gives the value – me_ Mar 28 '18 at 02:52
  • Possible duplicate of [best way to get the key of a key/value javascript object](https://stackoverflow.com/questions/6268679/best-way-to-get-the-key-of-a-key-value-javascript-object) – me_ Mar 28 '18 at 03:03

4 Answers4

3

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}`);
}
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
2

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]);
      });
Thanh Lam
  • 696
  • 5
  • 11
1

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/

edh4131
  • 60
  • 7
1

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>
Giacomo Ciampoli
  • 821
  • 3
  • 16
  • 33