coffeescript - manipulating json
coffeescript - manipulating json
如果我有数据,这只是逻辑问题:
[
{
from: 'user a',
to: 'user b'
},
{
from: 'user a',
to: 'user c'
},
{
from: 'user b',
to: 'user d'
},
{
from: 'user c',
to: 'user d'
},
{
from: 'user c',
to: 'user d'
}
]
我需要将数据处理为:
[
{
from: 'user a',
to: ['user b', 'user c']
},
{
from: 'user b',
to: ['user d']
},
{
from: 'user c',
to: ['user d']
}
]
我用了这个代码:
result = []
objTemp = obj
from = []
obj.map (o) ->
if o.from not in from
from.push o.from
to = []
objTemp.map (oo) ->
if oo.from is o.from and oo.to not in to
to.push oo.to
temp =
from: o.from
to: to
result.push temp
但结果并不是我所期望的,仍然有相同的"to"在相同的"from"中:
[
{
from: 'user a',
to: ['user b', 'user c']
},
{
from: 'user b',
to: ['user d']
},
{
from: 'user c',
to: ['user d', 'user d'] <-- the problem
}
]
你们是怎么用coffeescript解决的?
以下是我的操作方法:
res = []
obj.map (o) ->
for r in res when r.from is o.from
return (r.to.push o.to unless o.to in r.to)
res.push from: o.from, to: [o.to]
groupBy
和uniq
方法(我想还有chain
),我可能会使用下划线或短划线。如果您对它们的实现感兴趣,以便在原始coffeescript中完成,可以查看带注释的源代码。
http://underscorejs.org/docs/underscore.html
chain
/value
只允许我内联调用这些函数,而不是让临时变量来保存它们或使函数调用不那么明显。
fromUser = (x)-> x.from
toRelationships = (memo, items, index, list)->
key = _(items).pluck('from')[0]
vals = _.values(list[key])
memo[key] = _(vals).chain().pluck('to').uniq().value()
memo
result = _(data).chain().groupBy(fromUser).reduce(toRelationships, []).value()
# without chain
grouped = _(data).groupBy( fromUser )
result = _(grouped).reduce( toRelationships, [])
jsfiddle:http://jsfiddle.net/eaL6t1cn/2/
这是我的看法,我现在为没有像我希望的那样简洁而道歉。如果我使用jQuery(或其他第三方),这会更简单一些,但这里没有任何库。
a = [
{
from: 'user a',
to: 'user b'
},
{
from: 'user a',
to: 'user c'
},
{
from: 'user b',
to: 'user d'
},
{
from: 'user c',
to: 'user d'
},
{
from: 'user c',
to: 'user d'
}
]
c = {}
d = []
(value for value in a).forEach (v) ->
c[v.from] = do -> if not c[v.from] then [v.to] else ("#{c[v.from]},#{v.to}").
split(',').reduce ((p,c) ->
if c not in p then p.concat([c]) else [c] ), []
d.push {'from':v,'to':k} for v,k of c
console.log d
相关文章:
- jQuery匹配JSON对象的部分文本
- 在循环中分配json值时,值被覆盖
- 需要帮助设置json数组
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 使用JQuery解析JSON嵌套数组
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 如何使用json将对象列表从java转换为javascript
- 如何使用 node.js 比较两个 json 数组
- 如何将JSON数据导入我的ejs模板
- 区分JSON中的矩阵和列表列表
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 如何为json对象中的段发送array[]
- 根据id将json数组组合为一个json数组
- Json数据包含日期和时间格式
- AngularJS-在JSON选择器中使用变量名
- coffeescript - manipulating json