对象解构广告意外 key:value 对

Object destructuring adds unxexpected key:value pair

我正在使用 req.body 的解构来获取所有字段输入。 但是由于某种原因,_csrf 令牌被传入了??

代码如下:

 let bizReq = {
        logo,
        category,
        name,
        owner,
        phone,
        location,
        website,
        email,
      } = req.body;

    /// EG result (console.log(bizReq);)
    new biz:  {
      name: 'Jasmine Gregory',
      email: 'sojopo@mailinator.com',
      location: 'Itaque aperiam iusto',
      owner: { firstName: 'Mary', lastName: 'Garrett' },
      phone: '+1 523 308-3805',
      website: 'https://www.kezobazi.cm',
      category: 'Clothes',
      logo: 'https://eu.ui-avatars.com/api/? 
      background=89023E&color=fff&name=Jasmine+Gregory&length=2&size=512',
      _csrf: 'ATqvC5qR-h1JPRec_usro3V4Pb6jYv80Tj5Y' ----------????---------
   }

我哪里错了? 提前致谢

这不是很恰当的对象解构。

这里有一个例子,这样你就知道哪里出错了:

let obj = { a, b } = { a: 1, b: 2, c: 3 };
console.log(obj); // will print { a: 1, b: 2, c: 3 }

上面的let语句等同于:

let obj = ( { a, b } = { a: 1, b: 2, c: 3 } );

JS 中的赋值表达式(看起来像 p = q 的表达式)总是 return 表达式的右侧。这样就可以链接相等的运算符。表达式 r = p = q 被解析为 r = (p = q),为了让 rp 都被赋值 q(p = q) 必须 return q.

这意味着表达式 { a, b } = { a: 1, b: 2, c: 3 } 始终 return { a: 1, b: 2, c: 3 }。因此,代码等同于

let obj = { a: 1, b: 2, c: 3 };

这是你的错误。

如果您想限制某个对象拥有的键,请查看

如果您想从对象中过滤掉某些属性,请考虑使用 Rest Parameter

注: let newObj = {prop1, prop2} = obj等同于let newObj = obj.

const data = {
  name: "Jasmine Gregory",
  email: "sojopo@mailinator.com",
  location: "Itaque aperiam iusto",
  owner: { firstName: "Mary", lastName: "Garrett" },
  phone: "+1 523 308-3805",
  website: "https://www.kezobazi.cm",
  category: "Clothes",
  logo: "https://eu.ui-avatars.com/api/?",
  background: "89023E&color=fff&name=Jasmine+Gregory&length=2&size=512",
  _csrf: "ATqvC5qR-h1JPRec_usro3V4Pb6jYv80Tj5Y",
};

let {_csrf, ...bizReq} = data;

console.log(bizReq);

如果您想确保安全并仅解构您想要的属性,避免包含 req.body 中存在的任何恶意数据的风险。

您可以先从 req.bodydestructure 所需的属性,然后使用这些属性构造 bizReq 变量。

let { name, email, location, owner, phone, website, category, logo, background } = data;
let bizReq = { name, email, location, owner, phone, website, category, logo, background }

或者,如果你像我一样喜欢单排,你可以使用 IIFE

const data = {
  name: "Jasmine Gregory",
  email: "sojopo@mailinator.com",
  location: "Itaque aperiam iusto",
  owner: { firstName: "Mary", lastName: "Garrett" },
  phone: "+1 523 308-3805",
  website: "https://www.kezobazi.cm",
  category: "Clothes",
  logo: "https://eu.ui-avatars.com/api/?",
  background: "89023E&color=fff&name=Jasmine+Gregory&length=2&size=512",
  _csrf: "ATqvC5qR-h1JPRec_usro3V4Pb6jYv80Tj5Y",
};

let bizReq = (
  ({name, email, location, owner, phone, website, category, logo, background}) => 
  ({name,email,location,owner,phone,website,category,logo,background})
)(data);

console.log(bizReq);