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

问题描述 投票:0回答:7

说,我有一个对象:

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

有更好的方法吗?

javascript ecmascript-6
7个回答
64
投票

您可以通过解构的形式来实现它:

const user = { _id: 1234, firstName: 'John', lastName: 'Smith' };
const { _id, ...newUser } = user;
console.debug(newUser); 

浏览器支持:

扩展(

...
)语法是在 ES2018 中引入的,大多数浏览器甚至在 ES2018 最终确定之前就支持它。因此,从 2023 年开始,您可以依赖浏览器支持,除非您需要支持非常旧的浏览器。 或者,您可以将其与“转译”层(例如 Babel)一起使用。


7
投票

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


6
投票

您将进行两次浅复制:一次使用对象文字,另一次使用

Object.assign
。所以只需使用两者中的第一个:

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

3
投票

浏览对象键,将想要的属性键放入数组中,然后使用

Array.prototype.includes()
仅将它们复制到新对象中。

const account = {
  id: 123456,
  firstname: "John",
  lastname: "Doe",
  login: "john123",
  site_admin: false,
  blog: "https://opensource.dancingbear/",
  email: "[email protected]",
  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":"[email protected]","created_at":"2001-01-01T01:30:18Z"}

2
投票

最有效的很可能是常规循环

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)


1
投票

这个小功能将选择特定的键进行复制或从复制中排除。排除优先:

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


0
投票

如果“更好的方式”你只是在寻找一种看起来更优雅的方式,我通常这样做的方式是:

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

请注意,它用另外两个变量“污染”了作用域,但它很短,并且至少您指定了所需的变量,而不是要排除的变量。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.