4

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'

8 Answers 8

11

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)

Sign up to request clarification or add additional context in comments.

Comments

10

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);
}

Comments

2
try

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

Comments

2

Try this

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

Comments

1

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.

Comments

1

You can use the Object.keys(objectNameHere) method of the Object prototype to cycle through keys by name and enumeration.

Comments

0

Use Object.entries() to get a list of key/value pairs from your object. Then you can iterate over the pairs and display them with Array.forEach():

Object.entries({ a: 'hello', b: 3 }).forEach(([key, val]) => {
  console.log(key, val);
});

You can get a list of keys with Object.keys() and a list of values with Object.values():

const obj = { a: 'hello', b: 3 };

console.log(Object.keys(obj));
console.log(Object.values(obj));
console.log(Object.entries(obj));

Lastly, you can iterate over the object keys directly with a for...in loop, in which case you have to use bracket notation to access the property on your object:

const obj = { a: 'hello', b: 3 };

for (const key in obj) {
  console.log(key, obj[key]);
}

Comments

0

Try using the for..in operator

var obj = {
  Name: 'Mohsin ',
  Age: 20,
  Address: 'Peshawar',
}

for (var keys in obj) {
  console.log(keys, ':', obj[keys])
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.