const arr = [ {"name": "Rahul", "score": 89}, {"name": "Vivek", "score": 88}, {"name": "Rakesh", "score": 75}, {"name": "Sourav", "score": 82}, {"name": "Gautam", "score": 91}, {"name": "Sunil", "score": 79}, ];
Method 2: In this method we will use Map to store key => value in JavaScript. The map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value.
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.
No. Arrays can only have integers and strings as keys.
That's just what a JavaScript object is:
var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;
You can loop through it using for..in
loop:
for (var key in myArray) {
console.log("key " + key + " has value " + myArray[key]);
}
See also: Working with objects (MDN).
In ECMAScript6 there is also Map
(see the browser compatibility table there):
An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.
The keys of an Object are Strings and Symbols, where they can be any value for a Map.
You can get the size of a Map easily while you have to manually keep track of size for an Object.
If I understood you correctly:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
You can use Map.
- A new data structure introduced in JavaScript ES6.
- Alternative to JavaScript Object for storing key/value pairs.
- Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
Get value of the Map using key
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
Get size of the Map
console.log(map.size); // 2
Check key exists in Map
console.log(map.has('name')); // true
console.log(map.has('age')); // false
Get keys
console.log(map.keys()); // MapIterator { 'name', 'id' }
Get values
console.log(map.values()); // MapIterator { 'John', 11 }
Get elements of the Map
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
Print key value pairs
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
Print only keys of the Map
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
Print only values of the Map
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?
Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.
Simple Array eg.
$(document).ready(function(){
var countries = ['Canada','Us','France','Italy'];
console.log('I am from '+countries[0]);
$.each(countries, function(key, value) {
console.log(key, value);
});
});
Output -
0 "Canada"
1 "Us"
2 "France"
3 "Italy"
We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.
Simple Object (json)
$(document).ready(function(){
var person = {
name: "James",
occupation: "programmer",
height: {
feet: 6,
inches: 1
},
}
console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);
$.each(person, function(key, value) {
console.log(key, value);
});
});
Output -
My name is James and I am a 6 ft 1 programmer
name James
occupation programmer
height Object {feet: 6, inches: 1}
In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.
Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -
JSON array (array of objects) -
$(document).ready(function(){
var people = [
{
name: "James",
occupation: "programmer",
height: {
feet: 6,
inches: 1
}
}, {
name: "Peter",
occupation: "designer",
height: {
feet: 4,
inches: 10
}
}, {
name: "Joshua",
occupation: "CEO",
height: {
feet: 5,
inches: 11
}
}
];
console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");
$.each(people, function(key, person) {
console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
});
});
Output -
My name is Joshua and I am a 5 ft 11 CEO
My name is James and I am a 6 ft 1 programmer
My name is Peter and I am a 4 ft 10 designer
My name is Joshua and I am a 5 ft 11 CEO
Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With