How to create key value array in javascript

Learn how to create a key value array in javascript.

Arrays in javascript are not like arrays in other programming language. They are just objects with some extra features that make them feel like an array.

It is advised that if we have to store the data in numeric sequence then use array else use objects where ever possible.

And to create an associative array with a key value pair it is feasible to use objects only.

let obj = {};
obj['name'] = 'Prashant Yadav';
obj['website'] = 'learnersbucket.com';
obj['age'] = 24;
obj['hobbies'] = ['writing', 'reading', 'teaching'];

console.log(obj);
/*
Object {
  age: 24
  hobbies:["writing", "reading", "teaching"]
  name: "Prashant Yadav"
  website: "learnersbucket.com"
}
*/

There is an inbuilt data structure available in ES6 called Map which can be used to store the key value pair data.

Iterating key value array in javascript

We can use the For…in loop to enumerate through the stored values.

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

//"Prashant Yadav"
//"learnersbucket.com"
//24
//["writing", "reading", "teaching"]

As javascript objects can be extended, if you want to loop for the properties owned by the object only then we can restrict it using hasOwnProperty() method.

for(let key in obj){
   if(obj.hasOwnProperty(key)){
      console.log(obj[key]);
   }
}

//"Prashant Yadav"
//"learnersbucket.com"
//24
//["writing", "reading", "teaching"]