编写将我的json数组转换为我想要的格式的coffeescript函数的简洁方法是什么

时间:2016-10-07 18:44:49

标签: javascript coffeescript

我有这个json对象:

  op = [{"id":7,"d_set_id":1,"option_value_id":5,"product_id":3,"model":"1300","option_type":"Plunger Diameter","option":"5.0 inch Plunger Diameter","product":"Packing","route":"part_option_values","reqParams":null,"restangularized":true,"fromServer":true,"parentResource":{"route":"parts","parentResource":null,"id":"29"},"restangularCollection":false},{"id":9,"d_set_id":5,"option_value_id":11,"product_id":3,"model":"1300","option_type":"main drum diameter","option":"1.0  main drum diameter","product":"Packing","route":"part_option_values","reqParams":null,"restangularized":true,"fromServer":true,"parentResource":{"route":"parts","parentResource":null,"id":"29"},"restangularCollection":false}]

我写了这个函数把它转换成我想要的格式:

addItems: (op) ->
   variant = { 
    product_id: "undefined"
    model: "undefined"
    options: []
    product: "undefinded"
    option_value_ids: []
    quantity: 1
  }   
  op.forEach (obj,i) ->
    variant.product_id = obj.product_id
    variant.model = obj.model
    variant.options.push obj.option
    variant.product = obj.product
    variant.option_value_ids.push obj.option_value_id
  variant.options = variant.options.join(', ')
  items.push variant

它成功地将其更改为我想要的结果。

  items = [{"product_id":3,"model":"1300","options":"5.0 inch Plunger Diameter, 1.0  main drum diameter","product":"Packing","option_value_ids":[5,11],"quantity":1},{"product_id":3,"model":"1300","options":"5.0 inch Plunger Diameter, 1.0  main drum diameter","product":"Packing","option_value_ids":[5,11],"quantity":1}]

...但这似乎不是一种编写此功能的简洁方法。什么是更好的方式?

1 个答案:

答案 0 :(得分:0)

是的!这一切都可以用三个概念简洁地完成。地图,解构和对象速记符号(ES2015 / 6中的所有三个以及coffeescript)

options = []
ids = []

# We need to aggregate id's and options first
for {option_value_id, option} in op
  ids.push option_value_id
  options.push option

# Map through to the new Object
items = op.map ({ product_id, model, product}) ->
  {
    product_id
    model
    options: options
    product
    option_value_ids: ids
    quantity: 1
  } 

Array.map将获取一个数组并转换每个元素(在本例中为较大对象的子集)并返回一个新数组。我们将在参数中构造传入的对象,然后将它们缩写回对象格式。

Array Map

Object Destructuring

Shorthand Notation