Home > Back-end >  How to move a key value to an new array inside an object
How to move a key value to an new array inside an object

Time:05-19

From below object

{
    "user": {
        "id": 9,
        "email": "[email protected]",
    },
    "country": "USA",
    "first_name": "firstName",
    "last_name": "lastName",
}

How can we move first_name and last_name to a new array named names and push that into the same object as below

{
    "user": {
        "id": 9,
        "email": "[email protected]",
    },
    "country": "USA",
    "name": [
        {
            "first_name": "firstName",
            "last_name": "lastName",
        }
    ],
}

Thanks.

CodePudding user response:

Destructure the first_name and last_name from the rest of the properties, then create a new object; spreading out the old saved properties, and adding an array with an object with first_name and last_name properties.

const obj={user:{id:9,email:"[email protected]"},country:"USA",first_name:"firstName",last_name:"lastName"};

const { first_name, last_name, ...rest } = obj;

const newObj = {
  ...rest,
  names: [ { first_name, last_name } ]
};

console.log(newObj);

  • Related