Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an Object's specific keys in JavaScript?

I have an object and I want to iterate over some specific keys of that object. How to achieve this?

Consider the snippet below:

How can I iterate over table1,table2 and table3 keys and not all of them?

var table_object = {
  table1: "hello world",
  table1_name: "greetings_english.html",
  table2: "hola",
  table2_name: "greetings_spanish.html",
  table3: "Bonjour",
  table3_name: "greetings_french.html"
};
like image 630
Karan Dhir Avatar asked Oct 25 '17 07:10

Karan Dhir


1 Answers

You have to specify which keys you have to iterate through:

var table_object = {
  table1: "hello world",
  table1_name: "greetings_english.html",
  table2: "hola",
  table2_name: "greetings_spanish.html",
  table3: "Bonjour",
  table3_name: "greetings_french.html"
};

var keysToIterateThrough = ["table1", "table2", "table3"];
keysToIterateThrough.forEach(key => {
    var value = table_object[key];
    console.log(`key: ${key} => value: ${value}`);
})
like image 146
Faly Avatar answered Nov 02 '22 23:11

Faly