这个数组的需求怎么实现.请帮帮

我又一个这样结构的数组:
[{start: "2017-12-05", shiftOrderCode: "YEXF1002"}
{start: "2017-12-05", shiftOrderCode: "YYY"}
{start: "2017-12-06", shiftOrderCode: "Y001"}]
我怎么实现根据start,把start相同的shiftOrderCode放进一个数组,

阅读 3k
6 个回答

最大众的一种方式~

     var arr = [
       {start: "2017-12-05", shiftOrderCode: "YEXF1002"},
       {start: "2017-12-05", shiftOrderCode: "YYY"},
       {start: "2017-12-06", shiftOrderCode: "Y001"}
       ]

        function getCode(data,arr){
            var newArr = [];
            for(var i = 0; i < arr.length; i++){
                if(arr[i].start === data){
                    newArr.push(arr[i].shiftOrderCode);
                }
            }
            return newArr;
        }

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"]
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
}
推荐问题
宣传栏