基于内部对象数组对对象数组进行排序

时间:2018-03-19 10:31:39

标签: javascript ecmascript-6

我有一个对象数组:

   myData = [{
       name: "",
       lastName:"",
       moreData: [{
           left: 5,
           data: '',

        },
         {
           left: 3,
           data: '',

        }
     ]



   },
   {
       name: "",
       lastName:"",
       moreData: [{
           left: 8,
           data: '',

        },
         {
           left: 4,
           data: '',

        }
     ]
  }
  ],

我需要根据left:降序排列外部对象(主数组),降序, 所以我会有这样的结果:

   myData = [{
       name: "",
       lastName: "",
       moreData: [{
            left: 8,
            data: '',
     }]

  },
  {
       name: "",
       lastName: "",
       moreData: [{
            left: 5,
            data: '',
     }]

  },
{
       name: "",
       lastName: "",
       moreData: [{
            left: 4,
            data: '',
     }]

  },

{
       name: "",
       lastName: "",
       moreData: [{
            left: 3,
            data: '',
     }]

  }

  ]

或者有没有办法只对moreData进行排序,无论它属于哪个对象,然后保存,然后能够识别moreData属于哪个用户?

我需要根据在其数组中包含多个对象的列对数组进行排序。所以外部物体将被重复 使用JS,甚至可以在必要时使用Lodash。 有什么指导吗?

1 个答案:

答案 0 :(得分:1)

基于:Sort array

所以这是根据提供的stackoverlow链接的一个小例子。 它肯定不是最优雅的解决方案,因为代码对于您的情况非常静态,但您可以改进它。代码内部的解释。

myData = [{
    name: "Test",
    lastName:"1",
    moreData: [{
        left: 5,
        data: '',

     },
      {
        left: 3,
        data: '',

     },
     {
        left: 7,
        data: '',

     }
  ]



},
{
    name: "Test",
    lastName:"2",
    moreData: [{
        left: 8,
        data: '',

     },
      {
        left: 4,
        data: '',

     },
     {
        left: 9,
        data: '',

     }
  ]
}
];

代码:

myDataSplit = [];
//First we have to get ride of the multiple data in moreData
myData.forEach(level1 => {
    level1.moreData.forEach(level2 => {
        //Here we build a new array with a element for each moreData
        //If you want it more flexible push the whole level1 and replace moreData with level2
        myDataSplit.push({name: level1.name, lastName: level1.lastName, moreData: level2});
    });
});

//Now the compare like in the SO link
function compare(a,b) {
    if (a['moreData'].left < b['moreData'].left)
      return -1;
    if (a['moreData'].left > b['moreData'].left)
      return 1;
    return 0;
  }

  myDataSplit.sort(compare);
  console.log(myDataSplit);

结果就像你想要的那样:

​​​​Quokka #2 (node: v9.5.0)​​​​
​​​​​​​​​​
​​​​​[ { name: 'Test', lastName: '1', moreData: { left: 3, data: '' } },​​​​​
​​​​​  { name: 'Test', lastName: '2', moreData: { left: 4, data: '' } },​​​​​
​​​​​  { name: 'Test', lastName: '1', moreData: { left: 5, data: '' } },​​​​​
​​​​​  { name: 'Test', lastName: '1', moreData: { left: 7, data: '' } },​​​​​
​​​​​  { name: 'Test', lastName: '2', moreData: { left: 8, data: '' } },​​​​​
​​​​​  { name: 'Test', lastName: '2', moreData: { left: 9, data: '' } } ]​​​​​
  at ​​​myDataSplit​​​ ​quokka.js:61:2​