【问题标题】:How to nest element of an object inside the same object in javascript?如何在javascript中将对象的元素嵌套在同一对象内?
【发布时间】:2020-11-22 11:27:30
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript javascript-objects nested-object


    【解决方案1】:

    您可以使用扩展运算符轻松做到这一点:

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

    它只是将除nameage 之外的所有字段提取为friends

    示例:

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

    【讨论】:

      【解决方案2】:

      你可以明确地分配它

      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)

      【讨论】:

      • 谢谢,工作正常,但由于 friend:name 中的字段数量是动态的(上面的示例已简化以更好地显示我的问题)我需要使用代码而不是显式分配它们跨度>
      【解决方案3】:

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

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

      【讨论】:

      • 感谢 Ramesh,创意代码,唯一的问题是,在我的示例中,我上面写的所有键都以朋友 (friend1,friend2...) 开头,但在我的实际问题中,还有其他键不是按字母顺序相似。这种方法虽然非常有用,但我肯定会在其他问题中使用它
      • @Babak 很高兴为您提供帮助。如果您想得到答案,可以使用实际对象更新您的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2020-02-01
      • 2022-01-06
      相关资源
      最近更新 更多