问题
Is it possible to unpack some of the keys of an object to a new object?
Let's say, I want to copy 3 of the keys (a, b, c) from test object to a new object (abc). Below mention code will work.
const test = {a:1, b:2, c:3, d:4, e:5 };
const {a, b, c} = test;
const abc = { a, b, c, f: 6};
Is there any approach with which I can do it in a single statement?
There is one more approach.
const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = { ...test, f: 6};
But with this approach, I would later have to delete the unwanted keys (d, e in my case).
(Best Case Solution: If we don't have to keep track of unwanted keys. There can be n number of unwanted keys.)
回答1:
You can use object rest to destructure your initial object:
const test = {a:1, b:2, c:3, d:4, e:5 };
const {d, e, ...abc} = { ...test, f: 6};
console.log(abc);
回答2:
If you know the specific keys you're going to need in the new Object, I would use good old Object.assign
const extendInfo = { //object containing properties to extend other object }
const abc = { //your obj to extend }
Object.assign(abc, { a: extendInfo.a, b: extendInfo.b, c: extendInfo.c });
If you have a lot of props to extract the syntax becomes heavier and I would suggest a different approach, but if it's just a couple props, I think this is the cleaner and faster approach - and technically one line if you don't count variable declarations
回答3:
Using destructuring the params and IIFE (Immediately invoked function expressions), we can get rid of the unwanted keys in the source objects.
const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = (({a,b,c}) => ({a, b, c}))(test);
console.log(abc);
For ES5 compatibility,
var test = {a:1, b:2, c:3, d:4, e:5 };
var abc = (function (test) {
return {
a: test.a,
b: test.b,
c: test.c
}
})(test);
console.log(abc);
来源:https://stackoverflow.com/questions/50488096/es6-destructuring-assignment-unpack-some-properties-from-existing-object-to