[英]Javascript destructuring and assignment into new object
Lets say I have an object:假设我有一个 object:
let x = {a:1,b:2,c:3}
Now I can destructure as follows:现在我可以解构如下:
let {a,b} = x;
Is it possible to assign, (in the same line as the destructuring) these into a new object, the equivalent of?:是否可以将这些分配(与解构在同一行)到一个新的 object 中,相当于?:
let newObject = {a,b};
or (in pseudocode, I realise this doesn't work)或者(在伪代码中,我意识到这是行不通的)
let newObject = {a,b} = x;
or would I be required to use something as lodash _.pickBy
function?还是我需要使用 lodash _.pickBy
function 之类的东西?
let newObject = _.pickBy(x,['a','b'])
The reason I am asking is, I would like to do something like that for functions signatures:我问的原因是,我想为函数签名做类似的事情:
let fun = ({a,b}) => {
let args = {a,b}; // <----
}
It seems impossible, because, while looking the same, the destructuring assignment and object syntaxes are completely different things.这似乎是不可能的,因为虽然看起来一样,但解构赋值和对象语法是完全不同的东西。
let a, b;
{a,b} = x <-- {a,b} is not an object
If you try returning the result of destructuring assignment, it will still be returning x
, the full object.如果您尝试返回解构赋值的结果,它仍将返回x
,即完整的对象。
const result = {a,b} = x
// `result` is the full object
or或者
const result = ({a,b} = x);
// `result` is the full object
Anyway, writing such one-liners could be extremely confusing to teammates.无论如何,写这样的单行代码可能会让队友感到非常困惑。 It would raise my eyebrows during a peer review anyways :)无论如何,它会在同行评审期间引起我的注意:)
I think what you need is to filter the object by key without middle variables.我认为您需要的是在没有中间变量的情况下按键过滤 object 。
Here is my solutions:这是我的解决方案:
let x = {a:1,b:2,c:3}
let y = {}
;({a: y.a, b: y.b} = x)
let filterObjectByKeys = (object, keys) => Object.fromEntries(keys.map(k => [k, object[k]]))
let x = {a:1,b:2,c:3}
let y = filterObjectByKeys(x, ['a', 'b'])
Reference:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.