Object with Array - All Operations Covered (For Beginners)
Quick guide on most used operations on Arrays of Objects.
Table of contents
- 1. Understanding Objects in JavaScript
- 2. Understanding Arrays of Objects
- 3. Merging Objects and Arrays
- 3.1 Merging Two Objects (Object.assign************)
- 3.2 Merging Using Spread Operator
- 3.3 Merging Two Arrays (concat************)
- 3.4 Merging Arrays with Spread Operator
- 3.5 Merging Two Arrays of Objects with the Same ID (Overriding Values)
- 3.6 Using reduce() to Convert an Array into a Map
- I hope I was able to make you understand the different operations on Objects. Please feel free to comment down any questions you have on this.
Imagine you have a giant toy box filled with different toys. Now, if you want to find a specific toy, you need to open the box and look inside, right? In JavaScript, we do the same thing when working with objects and arrays. We open them up and search inside!
In this blog, we'll learn how to easily get values from objects and arrays using simple JavaScript techniques.
1. Understanding Objects in JavaScript
An object is like a cupboard with many shelves, each labeled with a name (key) and holding something (value).
const ram = { id: 1, name: "Ram Bhardwaj", age: 23 };
Here, id
, name
, and age
are keys, and 1
, "Ram Bhardwaj"
, and 23
are values.
1.1 for in
Loop (Finding Keys and Values)
This loop helps us go through each key inside an object.
for (let key in ram) {
// here values corresponding to keys in ram objets are retrieved as ram[key]
console.log(key, ram[key]);
}
Output:
id 1
name Ram Bhardwaj
age 23
1.2 Object.keys()
(Getting All Keys)
// this function returns an array of keys of the object that is passed in the Object.keys() functions.
console.log(Object.keys(ram)); // ["id", "name", "age"]
1.3 Object.values()
(Getting All Values)
// .values function returns the array of values of the object that is passed on the values() function.
console.log(Object.values(ram)); // [1, "Ram Bhardwaj", 23]
1.4 Object.entries()
(Getting Key-Value Pairs)
// entries() of Object returns the array of key and its values.
console.log(Object.entries(ram));
// [["id", 1], ["name", "Ram Bhardwaj"], ["age", 23]]
2. Understanding Arrays of Objects
An array of objects is like a list where each item is an object.
const people = [
{ id: 1, name: "Ram" },
{ id: 2, name: "Shyam" }
];
2.1 forEach()
(Going Through Each Person)
// this function goes to all the objects in the array and
// person is the a[i] in this case and we are printing the id and name of the person.
people.forEach(person => console.log(person.id, person.name));
Output:
1 Ram
2 Shyam
2.2 map()
(Creating a New List)
// map function goes to each element and performs the callback operation on each element and then stores the element in a new array
const names = people.map(person => person.name);
console.log(names); // ["Ram", "Shyam"]
2.3 filter()
(Finding Specific People)
// we can filter out the object with any condition applied
const shyamOnly = people.filter(person => person.name === "Shyam");
console.log(shyamOnly);
Output:
[{ id: 2, name: "Shyam" }]
2.4 find()
(Find the First Match)
const findRam = people.find(person => person.name === "Ram");
console.log(findRam);
Output:
{ id: 1, name: "Ram" }
2.5 reduce()
(Adding All IDs Together)
// notice how to extracted just the id from the current item and then added it.
const totalIds = people.reduce((sum, person) => sum + person.id, 0);
console.log(totalIds); // 3
3. Merging Objects and Arrays
3.1 Merging Two Objects (Object.assign
************)
const details1 = { id: 1, name: "Ram" };
const details2 = { age: 25 };
const merged = Object.assign({}, details1, details2);
// assign function merges the enumberable properties to the empy object.
console.log(merged); // { id: 1, name: "Ram", age: 25 }
3.2 Merging Using Spread Operator
const merged2 = { ...details1, ...details2 };
console.log(merged2);
3.3 Merging Two Arrays (concat
************)
const arr1 = [{ id: 1, name: "Ram" }];
const arr2 = [{ id: 2, name: "Bhardwaj" }];
const mergedArr = arr1.concat(arr2);
console.log(mergedArr);
3.4 Merging Arrays with Spread Operator
const mergedArr2 = [...arr1, ...arr2];
console.log(mergedArr2);
3.5 Merging Two Arrays of Objects with the Same ID (Overriding Values)
This might be overwhelming but please try to understand this as it will give u a clear picture of lot of things.
var join = function(arr1, arr2) {
let map = new Map();
console.log("Initial arr 1:", arr1); // [ { id: 1, x: 1 }, { id: 2, x: 9 } ]
console.log("Initial arr 2:", arr2); // [ { id: 3, x: 5 } ]
// Insert elements from arr1
for (let obj of arr1) {
map.set(obj.id, { ...obj }); // check the explaination below this loop
console.log(`Inserted from arr1: id=${obj.id}`, map.get(obj.id));
}
// map.set() is a method of Map that stores a key-value pair.
// key = obj.id → This means we are using the id of the object as the key in the map.
// value = { ...obj } → This ensures we are storing a new object (not a reference to the original object).
// { ...obj } (Spread Operator)
// The spread operator ... creates a shallow copy of obj.
// This ensures that we do not modify the original object from the input array.
// Merge or insert elements from arr2
for (let obj of arr2) {
if (map.has(obj.id)) {
console.log(`Merging id=${obj.id} from arr2:`, obj);
Object.assign(map.get(obj.id), obj); // Merge properties, arr2 overrides arr1
} else {
map.set(obj.id, { ...obj });
console.log(`Inserted from arr2: id=${obj.id}`, map.get(obj.id));
}
}
// Convert map values to an array and sort by id
let sortedArray = Array.from(map.values()).sort((a, b) => a.id - b.id);
console.log("Final Sorted Array:", sortedArray);
return sortedArray;
};
/**
* Example Usage
*/
console.log("Result 1:", join(
[{ "id": 1, "x": 1 }, { "id": 2, "x": 9 }],
[{ "id": 3, "x": 5 }]
));
/*
Console Output:
Initial arr 1: [ { id: 1, x: 1 }, { id: 2, x: 9 } ]
Initial arr 2: [ { id: 3, x: 5 } ]
Inserted from arr1: id=1 { id: 1, x: 1 }
Inserted from arr1: id=2 { id: 2, x: 9 }
Inserted from arr2: id=3 { id: 3, x: 5 }
Final Sorted Array: [ { id: 1, x: 1 }, { id: 2, x: 9 }, { id: 3, x: 5 } ]
Result 1: [ { id: 1, x: 1 }, { id: 2, x: 9 }, { id: 3, x: 5 } ]
*/
console.log("Result 2:", join(
[{ "id": 1, "x": 2, "y": 3 }, { "id": 2, "x": 3, "y": 6 }],
[{ "id": 2, "x": 10, "y": 20 }, { "id": 3, "x": 0, "y": 0 }]
));
/*
Console Output:
Initial arr 1: [ { id: 1, x: 2, y: 3 }, { id: 2, x: 3, y: 6 } ]
Initial arr 2: [ { id: 2, x: 10, y: 20 }, { id: 3, x: 0, y: 0 } ]
Inserted from arr1: id=1 { id: 1, x: 2, y: 3 }
Inserted from arr1: id=2 { id: 2, x: 3, y: 6 }
Merging id=2 from arr2: { id: 2, x: 10, y: 20 }
Inserted from arr2: id=3 { id: 3, x: 0, y: 0 }
Final Sorted Array: [ { id: 1, x: 2, y: 3 }, { id: 2, x: 10, y: 20 }, { id: 3, x: 0, y: 0 } ]
Result 2: [ { id: 1, x: 2, y: 3 }, { id: 2, x: 10, y: 20 }, { id: 3, x: 0, y: 0 } ]
*/
3.6 Using reduce()
to Convert an Array into a Map
const people = [
{ id: 1, name: "Ram" },
{ id: 2, name: "Shyam" }
];
const peopleMap = people.reduce((map, person) => {
map.set(person.id, person);
return map;
}, new Map());
// check the output yourself on you IDE
console.log(peopleMap);
I hope I was able to make you understand the different operations on Objects. Please feel free to comment down any questions you have on this.
Thanks for watching