写一个coffeescript函数,将json数组转换成我想要的格式,这是一种简洁的方式
What is a succinct way to write a coffeescript function that converts my json array into the format that I want
我有这个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}]
…但这似乎不是一个非常简洁的方法来写这个函数。什么是更好的方法?
是的!这一切都可以用三个概念简洁地完成。映射、解构和对象简写表示法(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
}
数组。map将接受一个数组并转换每个元素(在本例中是大对象的子集)并返回一个新的array。我们将在实参中解构传入的对象,然后将它们简化为对象格式。
数组映射对象Destructuring
速记符号
相关文章:
- 有没有一种方法可以从两个标签之间提取文本,并以我选择的格式输出
- 解析一个复杂的JavaScript表达式,将其改写为另一种格式
- 通过javascript将带有日期的字符串格式化为另一种格式
- 将JSON从一种格式转换为另一种格式
- 将 JSON 日期解析为另一种格式
- 将 json 文件转换为另一种格式
- TinyMCE 4:自动将一种块格式应用于新块
- 是Javascript的一种特殊字符串格式
- 我在变量中有一个日期格式.如何将该变量日期转换为另一种格式
- 用JavaScript将日期从一种格式转换为另一种格式
- 如何将字段数据从一种格式更改为另一种格式
- 是否有可能实现一种“;猜测;此日期格式基于数组中的信息
- 将REST JSON输出格式化为另一种格式
- 如何将一种日期格式转换为另一种
- 有没有一种原生的JavaScript方法来解析格式不佳的类似JSON的字符串
- 如果有一种方法可以在Javascript中以JSON格式访问对象属性
- 给定一个特定的日期,是否有一种方法可以在不知道日期是以哪种格式书写的情况下在自由文本文档中搜索该日期?
- 将欧洲价格转换为另一种格式
- 如何将json从一种格式转换为另一种格式
- 当我尝试从另一种日期格式创建一个日期对象时,结果日期正在改变它的值