【问题标题】:How to modifiy array object in javascript?如何在javascript中修改数组对象?
【发布时间】:2021-06-23 14:30:16
【问题描述】:

我有两个数组。 1)userDetails,engToGerman

const userDetails= [
  {
    firstName: 'Michael Scott',
    lastName: 'Dunder Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'
  },
  {
    firstName: 'Michael Scott',
    lastName: 'Dunder Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'

  },
  {
    firstName: 'Michael Scott',
    lastName: 'Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'

  },
]

engToGerman = [ 
   firstName: 'name',
   lastName: 'vorname'
]

现在我想修改用户详细信息,如下所示,我从 engToGerman 翻译了名字和姓氏,并想删除其余信息。

所以新的用户详细信息将如下所示:

const newUserDetails= [
  {
    name: 'Michael Scott',
    vorname: 'Dunder Mufflin',
  },
  {
    name: 'Michael Scott',
    vorname: 'Dunder Mufflin',

  },
  {
    name: 'Michael Scott',
    vorname: 'Mufflin',

  }
]

如何在不修改原始数组的情况下实现这一点?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用array#map 映射firstNamelastName

    const userDetails= [ { firstName: 'Michael Scott', lastName: 'Dunder Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, { firstName: 'Michael Scott', lastName: 'Dunder Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, { firstName: 'Michael Scott', lastName: 'Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, ],
        engToGerman = { firstName: 'name', lastName: 'vorname'},
        result = userDetails.map(o => ({ [engToGerman.firstName]: o.firstName, [engToGerman.lastName]: o.lastName }));
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      简单版类似于问题/回复here

      let cloned = JSON.parse(JSON.stringify(userDetails));

      然后你可以做你的法线数组贴图或任何你需要的东西。

      【讨论】:

      • 非常感谢。我在克隆阵列时遇到了困难。不错的解决方案@coolgoose
      【解决方案3】:

      解决办法

      const newUserDetails = [];
      
      for(let item in userDetails){ //iterate through the entire array
        const obj = {
          name : userDetails[item].firstname,
          vorname: userDetails[item].lastname
        }
        newUserDetails.push(obj);
      
      }
      

      【讨论】:

        猜你喜欢
        • 2020-01-12
        • 1970-01-01
        • 2020-11-15
        • 1970-01-01
        • 2022-11-25
        • 2019-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多