Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Move a Key in an Array of Objects using JavaScript?
Next article icon

How to Move a Key in an Array of Objects using JavaScript?

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using Object Destructuring and Map()
  • Using forEach() method
  • Using for...of Loop
  • Using reduce() method
  • Using for loop
  • Using Object.assign() and Array.map()

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' }
]



Next Article
How to Move a Key in an Array of Objects using JavaScript?

B

bhaveshna6qm1
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript Programs

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 Access Array of Objects in JavaScript ?
    Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
    4 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 JavaScript1. 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.JavaScriptcon
    3 min read
    How to convert a map to array of objects in JavaScript?
    A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
    6 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 funct
    5 min read
    How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
    Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish th
    3 min read
    How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
    An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to c
    2 min read
    How to Convert an Object into Array of Objects in JavaScript?
    Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences