0

我创建了一个表单来从用户那里获取一些信息,并且我想将他们的一些信息移动到一个嵌套对象中。原因是为了在前端更好地组织我的数据。

举个简单的例子,如何在 JavaScript 中用“oldInfo”创建下面的“newInfo”?

oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};

newInfo = {
  name: 'John',
  Age: '32',
  friends: {
    friend1: 'Michael',
    friend2: 'peter',
  },
};

我确定这一定是一个重复且简单的主题,但我找不到任何内容,因为我不知道要搜索什么关键字。

4

3 回答 3

1

您可以使用扩展运算符轻松完成此操作:

const { name, Age, ...friends } = oldInfo;
newInfo = { name, Age, friends };

它只是提取除nameageas之外的所有字段friends

例子:

const oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};
const { name, Age, ...friends } = oldInfo;
const newInfo = { name, Age, friends };
console.log(newInfo);

于 2020-08-02T02:26:59.330 回答
1

您可以明确分配它

const oldInfo = {
  name: "John",
  Age: "32",
  friend1: "Michael",
  friend2: "Peter",
}

const newInfo = {
  name: oldInfo.name,
  Age: oldInfo.Age,
  friends: {
    friend1: oldInfo.friend1,
    friend2: oldInfo.friend2,
  },
}

console.log(newInfo)

于 2020-08-02T02:33:57.480 回答
0

如果您有动态数量的friend: name键值对和其他不应嵌套的属性,friends则可以使用Object.entriesand reduce

const oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};

const newInfo = Object.entries(oldInfo).reduce((acc, [k, v]) => {
  if(k.startsWith('friend')) {
    acc.friends ? acc.friends[k] = v : acc.friends = {[k]: v};
  } else {
    acc[k] = v;
  }
  return acc;
},{});

console.log(newInfo);

于 2020-08-02T02:34:14.777 回答