js object destructuring assignment in deep
js object destructuring assignment in deep
obj = {k1: 1, k2: 2, k3: 3};
{k1: 1, k2: 2, k3: 3}
keys = ['k1', 'k2'];
(2) ["k1", "k2"]
const {
...keys,
} = obj;
VM380:2 Uncaught SyntaxError: Rest element must be last element
ks = Object.keys(obj);
(3) ["k1", "k2", "k3"]
ks.filter(k => keys.includes(k));
(2) ["k1", "k2"]
根据 keys 结构特定对象的 keys??? entries ??? Map ???
obj = {k1: 1, k2: 2, k3: 3};
// {k1: 1, k2: 2, k3: 3}
Object.entries(obj);
// (3) [Array(2), Array(2), Array(2)]0: (2) ['k1', 1]1: (2) ['k2', 2]2: (2) ['k3', 3]
keys = ['k1', 'k2'];
// (2) ['k1', 'k2']
// Object.entries(obj).filter([k, v] => keys.includes(k));
// Uncaught SyntaxError: Malformed arrow function parameter list
Object.entries(obj).filter(([k, v]) => keys.includes(k));
// (2) [Array(2), Array(2)]0: (2) ['k1', 1]1: (2) ['k2', 2]
Object.fromEntries(Object.entries(obj).filter(([k, v]) => keys.includes(k)));
// {k1: 1, k2: 2}
solution
Object.fromEntries && Object.entries
const obj = {k1: 1, k2: 2, k3: 3};
// {k1: 1, k2: 2, k3: 3}
const keys = ['k1', 'k2'];
// (2) ['k1', 'k2']
Object.fromEntries(Object.entries(obj).filter(([k, v]) => keys.includes(k)));
// {k1: 1, k2: 2}
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15006736.html
未经授权禁止转载,违者必究!