DEV Community

Avnish
Avnish

Posted on

How to Move a Key in an Array of Objects Using JavaScript

How to Move a Key in an Array of Objects Using JavaScript

In JavaScript, arrays of objects are a powerful data structure often used to store and manipulate complex data. Sometimes, you might need to move or rename a key within the objects in an array. This guide covers several methods to achieve this, complete with explanations and examples.


Table of Contents

  1. Using Object Destructuring and map()
  2. Using forEach() Method
  3. Using for...of Loop
  4. Using reduce() Method
  5. Using for Loop
  6. Using Object.assign() and map()

1. Using Object Destructuring and map()

This method leverages object destructuring and the map() function to iterate through the array, returning a new array of objects with the key moved or renamed.

Example:

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, index) => ({
    ...obj,
    index // Adding a new key
}));

console.log(newArray);
Enter fullscreen mode Exit fullscreen mode

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 }
]
Enter fullscreen mode Exit fullscreen mode

2. Using forEach() Method

With forEach(), you can iterate through the array and create a new array of modified objects.

Example:

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, index) => {
    newArray.push({ ...obj, index });
});

console.log(newArray);
Enter fullscreen mode Exit fullscreen mode

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 }
]
Enter fullscreen mode Exit fullscreen mode

3. Using for...of Loop

The for...of loop can iterate over the array, allowing you to create and push modified objects into a new array.

Example:

const array = [
    { name: 'John', age: 30, gender: 'male' },
    { name: 'Alice', age: 25, gender: 'female' },
    { name: 'Bob', age: 35, gender: 'male' }
];

const newArray = [];
for (const [index, obj] of array.entries()) {
    newArray.push({ ...obj, index });
}

console.log(newArray);
Enter fullscreen mode Exit fullscreen mode

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 }
]
Enter fullscreen mode Exit fullscreen mode

4. Using reduce() Method

The reduce() method can be used to transform the array into a new one with the key moved or renamed.

Example:

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, index) => {
    acc.push({ ...obj, index });
    return acc;
}, []);

console.log(newArray);
Enter fullscreen mode Exit fullscreen mode

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 }
]
Enter fullscreen mode Exit fullscreen mode

5. Using for Loop

A classic for loop can achieve the same result by manually iterating over the array and modifying each object.

Example:

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);
Enter fullscreen mode Exit fullscreen mode

Output:

[
  { id: 1, age: 25, fullName: 'Geeks' },
  { id: 2, age: 30, fullName: 'Geek' },
  { id: 3, age: 20, fullName: 'Geeks1' }
]
Enter fullscreen mode Exit fullscreen mode

6. Using Object.assign() and map()

This method combines Object.assign() with map() to move or rename keys immutably.

Example:

const moveKeyInArray = (arr, oldKey, newKey) => {
    return arr.map(obj => {
        const 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);
Enter fullscreen mode Exit fullscreen mode

Output:

[
  { id: 1, age: 25, fullName: 'John' },
  { id: 2, age: 30, fullName: 'Jane' },
  { id: 3, age: 22, fullName: 'Doe' }
]
Enter fullscreen mode Exit fullscreen mode

Conclusion

Choose the method that best suits your project requirements. For immutability, prefer map() or reduce(). For simpler use cases, the forEach() or for loop works just as well. By mastering these approaches, you can efficiently handle key manipulation in arrays of objects in JavaScript!

Top comments (0)