how to display both key and value in object using javascript?

14,040

Solution 1

You can use Object.entries.

let list = {eb: 'blue', et: 'green'}

const keyValue = (input) => Object.entries(input).forEach(([key,value]) => {
  console.log(key,value)
})


keyValue(list)
list = {er: 'yellow', ex: 'black'}
keyValue(list)

Solution 2

You can use for..in ,

for (var key in list) {
  console.log(key, list[key]);
}

With ES6, you can use Object.entries

for (let [key, value] of Object.entries(list)) {
    console.log(key, value);
}

Solution 3

try

for(var key in objects) {
        var value = objects[key];
    }

Solution 4

To avoid much computation and since V8 is great at handling JSON operations, you can simply JSON.stringify(obj) to give you all entries. Only problem is that you will have no control over how certain value types should be handled i.e. in that case, you will only remain with primitives as values.

Solution 5

Try this

const list = {er: 'yellow', ex: 'black'};
Object.keys(list).forEach(e=>console.log(e+"="+list[e]))

Share:
14,040

Related videos on Youtube

user3818576
Author by

user3818576

Updated on June 04, 2022

Comments

  • user3818576
    user3818576 almost 2 years

    I don't know if this is possible in javascript. I have a object that is dynamic. like

    const list = {eb: 'blue', et: 'green'}
    

    anytime my list value will change like

    const list = {er: 'yellow', ex: 'black'}
    

    How can get the key value in my object? like I'm going to display both key and value for it.

    const ikey = 'eb'
    const ivalue = 'blue'