【问题标题】:How to assign values to schema in shorthand如何以简写形式将值分配给模式
【发布时间】:2020-08-16 09:00:24
【问题描述】:

我正在将我的 JSON 值以速记方式分配给模式员工,但我收到如下错误,但我收到的错误是 Invalid shorthand property initializer,这是进行速记分配的语法方式吗

employee ={
  name={
    first = jsoncontent.first,
    middle =jsoncontent.middle
  }
  city = jsonContent.city,
  state = jsonContent.state,
  country = jsonContent.country,
  empId = jsonContent.empId,
}

【问题讨论】:

    标签: arrays node.js json for-loop foreach


    【解决方案1】:

    如果您将“双关语”作为简写,您可以这样做:

    const employee = { name, city };
    

    ...这要求顶级变量与您的属性同名。 JS 语法不允许您使用双关语语法递归到源对象的属性。但是,解构源对象可能会对您有所帮助:

    const { first, middle, city, state, country, empId } = jsoncontent;
    
    const employee = {
      name: { first, middle },
      city,
      state,
      country,
      empId,
    };
    

    或者你可能会发现像Aritra Chakraborty 这样的常用内联对象语法就足够了。

    【讨论】:

      【解决方案2】:

      我不知道任何速记来解析将 JSON 转换为您提到的另一个 JSON。

      你可能想这样做:

      const employee = {
        name: {
          first: jsoncontent.first,
          middle: jsoncontent.middle
        },
        city: jsonContent.city,
        state: jsonContent.state,
        country: jsonContent.country,
        empId: jsonContent.empId
      };
      

      【讨论】:

        猜你喜欢
        • 2021-12-22
        • 2018-09-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        • 2019-01-14
        • 1970-01-01
        • 1970-01-01
        • 2020-12-14
        相关资源
        最近更新 更多