【问题标题】:Is there a neater way to transform an array of objects有没有更简洁的方法来转换对象数组
【发布时间】:2019-10-29 21:29:06
【问题描述】:

我正在尝试转换一个数组,只更改了一个值。有没有更简洁的方法?

我附上了我尝试过的代码。它可以工作,但是我只是更改每个用户的联系人对象的数量,因此通过每个其他值创建一个新的格式化数组感觉有点多余。我怎样才能只替换联系电话而不遍历所有内容?

const users = [
  {
    id: "1",
    name: {
      givenNames: 'SpongeBob',
      last: 'SquarePants',
    },
    contact: {
      email: '',
      phone: '+1 123-1231234'
    },
  },
  {
    id: "2",
    name: {
      givenNames: 'Patrick',
      last: 'Star',
    },
    contact: {
      email: 'test2@test.com',
      phone: '+1 123-123-1234',
    },
  },
  {
    id: "3",
    name: {
      givenNames: 'Eugene Harold',
      last: 'Krabs',
    },
    contact: {
      email: 'test3@test.com',
      phone: '',
    },
  },
];

我的代码:

guestList() {
  const formattedArray = this.getSelectedGuests.map(user => {
     var rObj = {};
     rObj.id = user.id;
     rObj.name = user.name;
     rObj.contact = {
        email: user.contact.email,
        phone: user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
     };
   return rObj;
  });
  return formattedArray;
}

输出:

const users = [
  {
    id: "1",
    name: {
      givenNames: 'SpongeBob',
      last: 'SquarePants',
    },
    contact: {
      email: '',
      phone: '11231231234'
    },
  },
  {
    id: "2",
    name: {
      givenNames: 'Patrick',
      last: 'Star',
    },
    contact: {
      email: 'test2@test.com',
      phone: '11231231234',
    },
  },
  {
    id: "3",
    name: {
      givenNames: 'Eugene Harold',
      last: 'Krabs',
    },
    contact: {
      email: 'test3@test.com',
      phone: '',
    },
  },
];

【问题讨论】:

标签: javascript arrays vue.js


【解决方案1】:

由于您只需要更改contact 中的属性,您可以使用object destructuring 和rest,从对象的其余部分提取contact。

现在您可以将spread 对象的其余部分放入新对象中,创建一个新的contact 属性,将原始content 的内容传播到其中,并覆盖phone 属性。

function guestList(getSelectedGuests) {
  return getSelectedGuests.map(({ contact, ...rest }) => ({
    ...rest,
    contacts: {
      ...contact,
      phone: contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
    }
  }));
}

const users = [{"id":"1","name":{"givenNames":"SpongeBob","last":"SquarePants"},"contact":{"email":"","phone":"+1 123-1231234"}},{"id":"2","name":{"givenNames":"Patrick","last":"Star"},"contact":{"email":"test2@test.com","phone":"+1 123-123-1234"}},{"id":"3","name":{"givenNames":"Eugene Harold","last":"Krabs"},"contact":{"email":"test3@test.com","phone":""}}];

const result = guestList(users);

console.log(result);

如果你需要做很多不可变的转换,你可能需要考虑Immer。 Immer 允许您使用简单的变异代码,并使用Proxies 确保不变性。

const { produce } = immer;

function guestList(getSelectedGuests) {
  return getSelectedGuests.map(user => produce(user, draft => {
    draft.contact.phone = user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '')
  }));
}

const users = [{"id":"1","name":{"givenNames":"SpongeBob","last":"SquarePants"},"contact":{"email":"","phone":"+1 123-1231234"}},{"id":"2","name":{"givenNames":"Patrick","last":"Star"},"contact":{"email":"test2@test.com","phone":"+1 123-123-1234"}},{"id":"3","name":{"givenNames":"Eugene Harold","last":"Krabs"},"contact":{"email":"test3@test.com","phone":""}}];

const result = guestList(users);

console.log(result);

console.log(result[0] === users[0]); // false - a new object was created
&lt;script src="https://unpkg.com/immer/dist/immer.umd.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    好吧,只要您不使用公开不可变对象实现的库,这就是您必须编写的那种代码。根据您可以访问的 JS 方言,您可以编写稍微短一些的代码,但 buld 仍然存在:

    guestList() {
      return this.getSelectedGuests.map(user => ({
        user.id,
        user.name,
        contact: {
            user.contact.email,
            phone: user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
        }
      }));
    }
    

    如果您想使用不变性,我强烈建议您查看Immutable.js(可能是扩散最多的那个)或Seamless Immutable(扩散少得多,但我喜欢它)很多)。

    【讨论】:

      【解决方案3】:

      您无法避免访问每个用户,因为您必须更改每个用户的contact 属性。

      我只是更改每个用户的联系人对象的数量,所以 经历所有其他价值来创造感觉有点多余 一个新的格式化数组。

      您可以使用spread syntax 复制对象属性而无需显式复制它们。

      我还在正则表达式中添加了连字符 - 和空白字符 \s 以获得所需的输出。

      const users = [{ id: "1", name: { givenNames: 'SpongeBob', last: 'SquarePants', }, contact: { email: '', phone: '+1 123-1231234' }, }, { id: "2", name: { givenNames: 'Patrick', last: 'Star', }, contact: { email: 'test2@test.com', phone: '+1 123-123-1234', }, }, { id: "3", name: { givenNames: 'Eugene Harold', last: 'Krabs', }, contact: { email: 'test3@test.com', phone: '', }, } ];
      
      let result = users.map(user => ({
        ...user,
        contact: {
          ...user.contact,
          "phone": user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}-\s]/g, '')
        }
      }));
      
      console.log(result);

      在大多数情况下,您不必担心创建新数组,因为 JavaScript 及其运行的平台已针对此类场景进行了优化。

      但是如果你想就地修改数组,你可以使用forEach()来做到这一点。

      const users = [{ id: "1", name: { givenNames: 'SpongeBob', last: 'SquarePants', }, contact: { email: '', phone: '+1 123-1231234' }, }, { id: "2", name: { givenNames: 'Patrick', last: 'Star', }, contact: { email: 'test2@test.com', phone: '+1 123-123-1234', }, }, { id: "3", name: { givenNames: 'Eugene Harold', last: 'Krabs', }, contact: { email: 'test3@test.com', phone: '', }, } ];
      
      users.forEach(user => {
        user.contact.phone = user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}-\s]/g, '');
      });
      
      console.log(users);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 2015-12-14
        • 2014-03-13
        • 1970-01-01
        相关资源
        最近更新 更多