Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move a key value to an new array inside an object

From below object

{
    "user": {
        "id": 9,
        "email": "abcd@example.com",
    },
    "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": "abcd@example.com",
    },
    "country": "USA",
    "name": [
        {
            "first_name": "firstName",
            "last_name": "lastName",
        }
    ],
}

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:"abcd@example.com"},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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading