我又一个这样结构的数组:
[{start: "2017-12-05", shiftOrderCode: "YEXF1002"}
{start: "2017-12-05", shiftOrderCode: "YYY"}
{start: "2017-12-06", shiftOrderCode: "Y001"}]
我怎么实现根据start,把start相同的shiftOrderCode放进一个数组,
我又一个这样结构的数组:
[{start: "2017-12-05", shiftOrderCode: "YEXF1002"}
{start: "2017-12-05", shiftOrderCode: "YYY"}
{start: "2017-12-06", shiftOrderCode: "Y001"}]
我怎么实现根据start,把start相同的shiftOrderCode放进一个数组,
var arr = [{start: "2017-12-05", shiftOrderCode: "YEXF1002"},
{start: "2017-12-05", shiftOrderCode: "YYY"},
{start: "2017-12-06", shiftOrderCode: "Y001"}]
var temp = arr.reduce(function( obj , v ){
obj[v.start] ? obj[v.start].push( v.shiftOrderCode ) : ( obj[v.start] = []) && obj[v.start].push( v.shiftOrderCode )
return obj;
},{});
console.log(temp);
// 打印结果
// {
// "2017-12-05": ["YEXF1002", "YYY"],
// "2017-12-06": ["Y001"]
// }
console.log(temp["2017-12-05"]);//["YEXF1002", "YYY"]
参考链接:https://segmentfault.com/q/10...
https://segmentfault.com/q/10...
对您有很大的帮助!这边我就不帮忙实现了!
let arr = [
{start: "2017-12-05", shiftOrderCode: "YEXF1002"},
{start: "2017-12-05", shiftOrderCode: "YYY"},
{start: "2017-12-06", shiftOrderCode: "Y001"}
]
let temp = arr.reduce((pre, cur) => {
if(!pre[cur.start]){
pre[cur.start] = []
}
pre[cur.start].push(cur.shiftOrderCode)
return pre
})
console.log(temp)
用 lodash 比较轻松
const _ = require("lodash");
const data = [
{ start: "2017-12-05", shiftOrderCode: "YEXF1002" },
{ start: "2017-12-05", shiftOrderCode: "YYY" },
{ start: "2017-12-06", shiftOrderCode: "Y001" }
];
const result = _(data).groupBy(m => m.start)
.mapValues(list => list.map(m => m.shiftOrderCode))
.value();
console.log(result);
方法很多,用forEach也是可以的
function dataFilter(arr) {
const temp = {}
arr.forEach((val) => {
temp[val.start] = temp[val.start] || []
temp[val.start].push(val.shiftOrderCode)
})
return temp
}
8 回答4.5k 阅读✓ 已解决
6 回答3k 阅读✓ 已解决
5 回答2.6k 阅读✓ 已解决
5 回答6.2k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
3 回答2.4k 阅读
4 回答2.7k 阅读✓ 已解决
最大众的一种方式~