How to Move a Key in an Array of Objects using JavaScript?
Last Updated :
18 Jul, 2024
The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.
You can move or add a key to these types of arrays using the below methods in JavaScript:
Using Object Destructuring and Map()
This method uses the map() function along with object destructuring to generate an array of objects with the current key at a new place.
Example: The below code implements the above-discussed methods to move a key in an array of objects.
JavaScript
const array = [
{
name: 'John',
age: 30,
gender: 'male'
},
{
name: 'Alice',
age: 25,
gender: 'female'
},
{
name: 'Bob',
age: 35,
gender: 'male'
}
];
const newArray = array.map(
(obj, ind) => (
{
...obj,
['index']: ind
}));
console.log(newArray);
Output[
{ name: 'John', age: 30, gender: 'male', index: 0 },
{ name: 'Alice', age: 25, gender: 'female', index: 1 },
{ name: 'Bob', age: 35, gender: 'male', index: 2 }
]
Using forEach() method
Loop through every item in the array using the forEach() method, and do it for every item move the key to the desired place.
Example: The below code implements the above-discussed methods to move a key in an array of objects.
JavaScript
const array = [
{
name: 'John',
age: 30,
gender: 'male'
},
{
name: 'Alice',
age: 25,
gender: 'female'
},
{
name: 'Bob',
age: 35,
gender: 'male'
}
];
const newArray = [];
array.forEach(
(obj, ind) => (
newArray.push({
...obj,
['index']: ind
})));
console.log(newArray);
Output[
{ name: 'John', age: 30, gender: 'male', index: 0 },
{ name: 'Alice', age: 25, gender: 'female', index: 1 },
{ name: 'Bob', age: 35, gender: 'male', index: 2 }
]
Using for...of Loop
Navigate every object in the array of objects using a for...of loop, and create another object that puts the key at the desired position for each object in the array.
Example: The below code implements the above-discussed methods to move a key in an array of objects.
JavaScript
const array = [
{
name: 'John',
age: 30,
gender: 'male'
},
{
name: 'Alice',
age: 25,
gender: 'female'
},
{
name: 'Bob',
age: 35,
gender: 'male'
}
];
const newArray = [];
for (const [ind, obj] of
array.entries()) {
newArray.push(
{
...obj,
['index']: ind
});
}
console.log(newArray);
Output[
{ name: 'John', age: 30, gender: 'male', index: 0 },
{ name: 'Alice', age: 25, gender: 'female', index: 1 },
{ name: 'Bob', age: 35, gender: 'male', index: 2 }
]
Using reduce() method
We can use the reduce() method to change the array of objects where the key will be moved to the required position within the objects.
Example: The below code implements the above-discussed methods to move a key in an array of objects.
JavaScript
const array = [
{
name: 'John',
age: 30,
gender: 'male'
},
{
name: 'Alice',
age: 25,
gender: 'female'
},
{
name: 'Bob',
age: 35,
gender: 'male'
}
];
const newArray = array.reduce(
(acc, obj, ind) => {
acc.push(
{
...obj,
['index']: ind
});
return acc;
}, []);
console.log(newArray);
Output[
{ name: 'John', age: 30, gender: 'male', index: 0 },
{ name: 'Alice', age: 25, gender: 'female', index: 1 },
{ name: 'Bob', age: 35, gender: 'male', index: 2 }
]
Using for loop
The code moves a key within each object in an array by iterating with a `for` loop, checking for the old key, assigning its value to a new key, deleting the old key, and returning the modified array.
Example:
JavaScript
const arr = [
{ id: 1, name: 'Geeks', age: 25 },
{ id: 2, name: 'Geek', age: 30 },
{ id: 3, name: 'Geeks1', age: 20 }
];
const moveKey = (arr, oldKey, newKey) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].hasOwnProperty(oldKey)) {
arr[i][newKey] = arr[i][oldKey];
delete arr[i][oldKey];
}
}
return arr;
};
const newArr = moveKey(arr, 'name', 'fullName');
console.log(newArr);
Output[
{ id: 1, age: 25, fullName: 'Geeks' },
{ id: 2, age: 30, fullName: 'Geek' },
{ id: 3, age: 20, fullName: 'Geeks1' }
]
Using Object.assign() and Array.map()
In this approach, we use Object.assign() in combination with Array.map() to create a new array of objects with the key moved to the desired position. This method constructs a new object for each element in the array, ensuring immutability and preserving the original array.
Example: The below code demonstrates how to move a key in an array of objects using Object.assign() and Array.map().
JavaScript
const moveKeyInArray = (arr, oldKey, newKey) => {
return arr.map(obj => {
let newObj = {};
Object.assign(newObj, obj); /
if (oldKey in newObj) {
newObj[newKey] = newObj[oldKey];
delete newObj[oldKey];
}
return newObj;
});
};
const data = [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 },
{ id: 3, name: 'Doe', age: 22 }
];
const result = moveKeyInArray(data, 'name', 'fullName');
console.log(result);
Output[
{ id: 1, age: 25, fullName: 'John' },
{ id: 2, age: 30, fullName: 'Jane' },
{ id: 3, age: 22, fullName: 'Doe' }
]
Similar Reads
How to Create an Array of Object Literals in a Loop using JavaScript?
Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read
How to Sort an Array of Objects Based on a Key in JavaScript ?
In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
3 min read
How to Push an Object into an Array using For Loop in JavaScript ?
JavaScript allows us to push an object into an array using a for-loop. This process consists of iterating over the sequence of values or indices using the for-loop and using an array manipulation method like push(), to append new elements to the array. We have given an empty array, and we need to pu
3 min read
How to Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript 1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly. [GFGTABS] J
4 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function(
3 min read
How to modify an object's property in an array of objects in JavaScript ?
Modifying an object's property in an array of objects in JavaScript involves accessing the specific object within the array and updating its property. Using the Array.map() methodUsing the map() method to create a new array by transforming each element of the original array based on a specified func
5 min read
How to convert Object's array to an array using JavaScript ?
Given an array of objects and the task is to convert the object values to an array with the help of JavaScript. There are two approaches that are discussed below: Approach 1: We can use the map() method and return the values of each object which makes the array. Example: [GFGTABS] html <!DOCTYPE
2 min read
How to access an object having spaces in the object's key using JavaScript ?
Given an object and the task is to access the object in which the key contains spaces. There are a few methods to solve this problem which are discussed below: Approach 1: Create an object having space-separated keys.Use square bracket notation instead of dot notation to access the property. Example
2 min read
Sort an array of objects using Boolean property in JavaScript
Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below: Table of Content Using Array.sort() Method and === OperatorUsing Array.sort() and reverse() MethodsUsing a
2 min read
How to convert an Object {} to an Array [] of key-value pairs in JavaScript?
Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). Methods to convert the Objects to JavaScript Array: 1. Using Obj
3 min read