简体   繁体   English

在JavaScript中转换数据的最佳做法

[英]Best Practice when converting data in JavaScript

I'm currently working with a payload that is string and im parsing is using JSON.parse(payload) . 我目前正在使用字符串有效负载,并且即时消息解析使用JSON.parse(payload) My question is, once I convert the payload I need to access at least 5 properties within the newly created JSON object and it is quite nested. 我的问题是,转换有效负载后,我需要访问新创建的JSON对象中的至少5个属性,并且该属性非常嵌套。 My current implementation is: 我当前的实现是:

 ....then(payload => {
   return ({
       obj1: JSON.parse(payload).field.obj1
       obj2: JSON.parse(payload).field.obj2
       obj3: JSON.parse(payload).field.obj3
       obj4: JSON.parse(payload).field.obj4
       obj5: JSON.parse(payload).field.obj5
     });    
   })

I feel like this is to much repetition and feel this way would work better in terms of readability (even then it is not that clean): 我觉得这要重复很多,并觉得这种方式在可读性方面会更好(即使那样也不是很干净):

   ....then(payload => {
       let jsonObj = JSON.parse(payload)
       return ({
           obj1: jsonObj.field.obj1
           obj2: jsonObj.field.obj2
           obj3: jsonObj.field.obj3
           obj4: jsonObj.field.obj4
           obj5: jsonObj.field.obj5
         });    
       })

Can anyone suggest the best way to execute this in terms of readability and performance? 有人可以在可读性和性能方面建议最佳的执行方式吗?

NOTE: This is used within a promise.all() so the above will iterate over X promises. 注意:这是在promise.all()因此以上内容将迭代X个promise。

You could use a destructuring assignment and return an object with short hand properties . 您可以使用解构分配并返回具有简短属性的对象。

let { field: { obj1, obj2, obj3, obj4, obj5 } } = JSON.parse(payload);
return { obj1, obj2, obj3, obj4, obj5 };

Edit 编辑

Better yet, just parse the whole thing and return the field object. 更好的是,只需解析整个内容并返回字段对象。 I think that would work. 我认为那行得通。 (I'm a little sleep deprived though!) (虽然我有点睡眠不足!)

....then(payload => {
   return (JSON.parse(payload).field);
})

End Edit 结束编辑

  1. Parse the whole response to find the field obj. 解析整个响应以找到field obj。
  2. Stringify the field obj to prepare it to be copied. 字符串化field obj以准备将其复制。
  3. Return the parsed field obj. 返回已解析的field obj。

- --

....then(payload => {
   return (JSON.parse(JSON.stringify(JSON.parse(payload).field)));
})

If you use Bluebird you can also do (as you already use Promise.all ) 如果您使用Bluebird那么您也可以这样做(因为您已经在使用Promise.all

const payloadPromises = Promise.map(sourcePromises, JSON.parse);
return Promise
  .all(payloadPromises)
  .then(payloads => payload.map(payload => ({
    obj1: payload.field.obj1,
    obj2: payload.field.obj2,
  }));

But actually just variable (your second approach) is completely fine. 但是实际上只是可变的(您的第二种方法)完全可以。 Perhaps, you should only use const instead of let in this case. 在这种情况下,也许只应使用const而不是let

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM