如何根据不同的属性对对象数组进行排序?

时间:2019-05-29 11:30:16

标签: javascript arrays object topological-sort

我需要对元素为对象的数组进行排序。我想按特定顺序填写下拉列表

[{ id: 1, name: "Country", parent: null, level: 0 }, 
{ id: 48, name: "Village1", parent: 16, level: 2 }, 
{ id: 17, name: "City1", parent: 1, level: 1 }, 
{ id: 15, name: "Village4", parent: 16, level: 2 }, 
{ id: 61, name: "City2", parent: 1, level: 1 }, 
{ id: 16, name: "City3", parent: 1, level: 1 }, 
{ id: 85, name: "City6", parent: 1, level: 1 }, 
{ id: 31, name: "Village2", parent: 77, level: 2 }, 
{ id: 76, name: "City4", parent: 1, level: 1 }, 
{ id: 77, name: "City5", parent: 1, level: 1 }, 
{ id: 79, name: "Village3", parent: 77, level: 2 }]

我要实现的目标是获得一个下拉列表,该下拉列表首先显示国家/地区(父级null),然后显示其子级,但是如果这些子级也有子级,则应立即出现在下面,如下所示:
-国家
-City1
-City2
-City3
-乡村1
-乡村2
-City4
。 。 。 等等。

有人可以帮我吗?我在这里真的很挣扎...

3 个答案:

答案 0 :(得分:1)

我认为您想创建一棵树,下面是一半的答案,我认为它可以帮助您。

let arrOfObjectData = [{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }];

let allParent = arrOfObjectData.filter((ele) => ele.parent == 1);
let treeArrOfObject = [];
allParent.forEach(element => {
	let findChild = arrOfObjectData.filter((elm) => elm.parent == element.id);
	treeArrOfObject.push({ parent: findChild, children: findChild });
});
console.log(treeArrOfObject);

答案 1 :(得分:0)

您可以先将所有子级添加到其父级的属性中。

[
  {
    id: 1, 
    name: "Country", 
    children:[{id: 17, name: "Village1", parent: 1, level: 1}]
  },    
  {
    id: 2, 
    name: "Country2", 
    children:[{id: 19, name: "Village2", parent: 2, level: 1}]
  },    
]

然后遍历父母,将其输出并嵌套遍历每个父母的孩子并输出的循环

parents.forEach((parent) => {
  //output parent
  parent.children.forEach((child) => {
  //output child
  });
});

答案 2 :(得分:-2)

应该这样做:

let finalArray = [];
originalArray.map(x => {
   if(x.name === 'Country') {finalArray[0] = x}
   if(x.name === 'City1') {finalArray[1] = x}
   if(x.name === 'City2') {finalArray[2] = x}
   if(x.name === 'City3') {finalArray[3] = x}
   if(x.name === 'Village1') {finalArray[4] = x}
   if(x.name === 'Village2') {finalArray[5] = x}
   if(x.name === 'City4') {finalArray[6] = x}
 })