Coc*_*Hot 2 javascript arrays json underscore.js lodash
我是Lodash的新手并试图解决这个问题,但可以找到一个很好的方法来做到这一点.
我有一个从数据库返回的对象数组.数据结构如下:
var data = [{
index: 1,
Aoo: "a1",
Boo: 'b2',
}, {
index: 1,
Aoo: "a2",
Boo: 'b2',
}, {
index: 2,
Aoo: "a3",
Boo: 'b3',
}];
Run Code Online (Sandbox Code Playgroud)
我想第一组由指数的对象,然后组属性"AOO"和"嘘",并把它称为数组属性param.
var result = [{
index: 1,
param: [{
Aoo: 'A1',
Boo: 'B1'
},{
Aoo: 'A2',
Boo: 'B2',
}]
}, {
index: 2,
param: [{
Aoo: 'A3',
Boo: 'B3'
}]
}
]
Run Code Online (Sandbox Code Playgroud)
我可以手动完成,但我想充分利用Lodash的功能.现在我只知道我可以通过使用实现分组的第一步,_.groupBy('index')我仍然坚持下一步做什么.
你快到了.以下是使用lodash完成此操作的方法
var data = [{
index: 1,
Aoo: "a1",
Boo: 'b2',
}, {
index: 1,
Aoo: "a2",
Boo: 'b2',
}, {
index: 2,
Aoo: "a3",
Boo: 'b3',
}];
var result = _.chain(data)
.groupBy('index')
.map((value, key) => {
return {
index: Number(key), //the index was transformed into a string, this will make it a number again.
param: _.map(value, o => _.omit(o, 'index'))//do not include the index key from the previous objects
}
})
.value();
console.log(result);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
不可否认,第二部分比分组略显棘手,但不是很多.由于索引为您提供了以下结构:
{
"1": [
{
"index": 1,
"Aoo": "a1",
"Boo": "b2"
},
{
"index": 1,
"Aoo": "a2",
"Boo": "b2"
}
],
"2": [
{
"index": 2,
"Aoo": "a3",
"Boo": "b3"
}
]
}Run Code Online (Sandbox Code Playgroud)
你真正想做的就是重复它,让每个键成为index属性然后你留下一系列初始对象.每个都需要通过删除index密钥进行转换,并将其分配给param值.这是一次性使用.map.不幸的是,它不像它看起来那么漂亮,但我认为这是你用Lodash的基本版本做的最好的.
如果要选择键的特定子集,而不是"除索引之外的所有",则可以使用_.pick而不是_.omit执行此操作.这是这样的:
var data = [{
index: 1,
Aoo: "a1",
Boo: 'b2',
Coo: "c1"
}, {
index: 1,
Aoo: "a2",
Boo: 'b2',
Coo: "c2"
}, {
index: 2,
Aoo: "a3",
Boo: 'b3',
Coo: "c3"
}];
var result = _.chain(data)
.groupBy('index')
.map((value, key) => {
return {
index: Number(key), //the index was transformed into a string, this will make it a number again.
param: _.map(value, o => _.pick(o, ['Aoo', 'Boo']))//do not include the index key from the previous objects
}
})
.value();
console.log(result);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
因此,即使数据中有一个额外的键,我们也会得到相同的结果.