简体   繁体   English

如何根据另一个 object 对数组 object 进行排序

[英]how to sort array object based on another object

it possible to sort and rearrange an array that looks like this:可以对如下所示的数组进行排序和重新排列:

items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]

to match the arrangement of this object:为了匹配这个 object 的排列:

 Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }

Here is the output I'm looking for:这是我正在寻找的 output:

 items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]

You could check if the index is supplied and if not take a lage value for sorting by delta of two items.您可以检查是否提供了索引,如果没有提供按两个项目的增量排序的较大值。

 var data = { items: [{ id: '5', name: 'wa' }, { id: '3', name: 'ads' }, { id: '1', name: 'fdf' }] }, sequence = { 5: { index: 1 }, 1: { index: 0 } }; data.items.sort(({ id: a }, { id: b }) => (a in sequence? sequence[a].index: Number.MAX_VALUE) - (b in sequence? sequence[b].index: Number.MAX_VALUE) ); console.log(data.items);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

JavaScript specifically, First you have to apply loop to your array "items": JavaScript 具体来说,首先你必须对你的数组“项目”应用循环:

`
 let newArr = [];
 items.map(obj=>{

//obj will be the element of items array, here it is an object.

 if(Item_sequence.obj[id] !== undefined) {
   /*this condition will be satisfied when id from items array will be present as a 
   key in Item_sequence array*/

   insertAt(newArr, Item_sequence.obj[id] , obj) 
  }
 else{
   newArr.push(obj);
 }
})
//After checking on whole array here you assign a newArr value to items array.
items=newArr;

Hope that it will help you.希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM