为了账号安全,请及时绑定邮箱和手机立即绑定

如何对数组的对象进行分组和分离

如何对数组的对象进行分组和分离

繁花不似锦 2022-10-27 15:07:35
如何对来自服务器的数组对象进行分组和分离。像这样的数组:(MOVINGSTATEs这表示停止和m移动。XPOINT 和 YPOINT 这表示汽车的经纬度。)[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316},..]我想如果一些MOVINGSTATEContinuous sgoto new array 以及何时MOVINGSTATE更改为mgoto new array 并再次MOVINGSTATE更改为s goto new array。另一个主数组的所有这些新数组对象。我用loadashvar aaa = _loadash.groupBy(props,'MOVINGSTATE')但输出这个:{m:Array(2),s:Array(3)}我想要这样的输出:[ [  {MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},  {MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275}  ], [  {MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},  {MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583} ], [  {MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316} ]]谢谢你的帮助
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

尝试这个:


let arr = 

[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},

{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},

{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},

{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},

{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316}];


  let result =  arr.reduce( (accumulator, cur) => {

    const key = cur["MOVINGSTATE"];

    const keyExists = accumulator.find(obj => obj.key === key);

    if (!keyExists) {

      accumulator.push({key,value:[cur]});

      return accumulator;      

    } else if(accumulator[accumulator.length -1] && accumulator[accumulator.length -1].key === key){

        accumulator[accumulator.length -1].value.push(cur);

        return accumulator;

    } else {

      accumulator.push({key,value:[cur]});

      return accumulator; 

    }

        

  }, [])

  .map(obj => obj.value)


查看完整回答
反对 回复 2022-10-27
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信