在JavaScript中从对象复制某些属性的最有效方法是什么?

时间:2016-11-12 12:03:39

标签: javascript ecmascript-6

说,我有一个对象:

const user = {_id: 1234, firstName: 'John', lastName: 'Smith'}

我想创建另一个没有_id键的对象:

const newUser = {firstName: 'John', lastName: 'Smith'}

我正在使用它:

const newUser = Object.assign({}, {firstName: user.firstName, lastName: user.lastName})

有更好的方法吗?

6 个答案:

答案 0 :(得分:19)

您可以通过解构和对象休息属性来实现它:

const user = {_id: 1234, fistName: 'John', lastName: 'Smith'}
const {_id, ...rest} = user;
console.log(rest);

rest/rpread properties仍为ecmascript's proposal(目前处于第3阶段)。你可以将它用于像babel这样的转换层。

答案 1 :(得分:4)

使用Array#reduce方法使用Object.keys方法。

const user = {
  _id: 1234,
  fistName: 'John',
  lastName: 'Smith'
};

var res = Object.keys(user).reduce(function(obj, k) {
  if (k != '_id') obj[k] = user[k];
  return obj;
}, {});

console.log(res);

答案 2 :(得分:1)

效率最高的很可能是常规循环

const user = {_id: 1234, fistName: 'John', lastName: 'Smith'};
let   obj  = {}, key;

for (key in user) {
  if ( key !== '_id' ) obj[key] = user[key];
}

console.log(obj)

答案 3 :(得分:1)

您正在进行两次浅拷贝:一次使用对象文字,另一次使用Object.assign。所以只需使用两者中的第一个:

const newUser = {firstName: user.firstName, lastName: user.lastName};

答案 4 :(得分:0)

这个小功能将选择特定键来复制或排除复制。排除优先:

function copy(obj, include=[], exclude=[]) {

  return Object.keys(obj).reduce((target, k) => {

    if (exclude.length) {
      if (exclude.indexOf(k) < 0) target[k] = obj[k];
    } else if (include.indexOf(k) > -1) target[k] = obj[k];
    return target;
  }, {});
}

// let's test it
const user = {
  _id: 1234,
  firstName: 'John',
  lastName: 'Smith'
};

// both will return the same result but have different uses.
console.log(
  'include only firstName and lastName:\n', 
  copy(user, ['firstName', 'lastName'])
);
console.log(
  'exclude _id:\n',
  copy(user, null, ['_id'])
);

答案 5 :(得分:0)

浏览对象键,将需要的属性键放入数组中,然后使用Array.prototype.includes()将这些键仅复制到新对象中。

const account = {
  id: 123456,
  firstname: "John",
  lastname: "Doe",
  login: "john123",
  site_admin: false,
  blog: "https://opensource.dancingbear/",
  email: "john123@example.com",
  bio: "John ❤️ Open Source",
  created_at: "2001-01-01T01:30:18Z",
  updated_at: "2020-02-16T21:09:14Z"
};

function selectSomeProperties(account) {
return Object.keys(account).reduce(function(obj, k) {
    if (["id", "email", "created_at"].includes(k)) {
        obj[k] = account[k];
    }
    return obj;
  }, {});
}
const selectedProperties = selectSomeProperties(account);
console.log(JSON.stringify(selectedProperties))

结果:

{"id":123456,"email":"john123@example.com","created_at":"2001-01-01T01:30:18Z"}