如何将键值移动到对象内的新数组

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

从物体下方

{
    "user": {
        "id": 9,
        "email": "abcd@example.com",
    },
    "country": "USA",
    "first_name": "firstName",
    "last_name": "lastName",
}

我们如何将 first_namelast_name 移动到名为 names 的新数组并将其推入与下面相同的对象中

{
    "user": {
        "id": 9,
        "email": "abcd@example.com",
    },
    "country": "USA",
    "name": [
        {
            "first_name": "firstName",
            "last_name": "lastName",
        }
    ],
}

谢谢。

Destructure the first_name and last_name from the rest of the properties, then create a new object; spreading out 旧的已保存属性,并添加一个包含具有 first_namelast_name 属性的对象的数组。

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);