基于关键字循环对象数组

时间:2018-04-06 03:50:06

标签: javascript arrays loops sorting object

按特定顺序对对象数组进行排序。

var details = [{
"name": "john",
"place":"new york"
},{
"name": "mark",
"place":"chicago"
},{
"name": "tom",
"place":"san jose"
},{
"name": "dansk",
"place":"new jersey"
}],

地图应按以下顺序显示列表,基本上我们需要决定输出模式,我们应该能够改变顺序:

san jose,
new york,
chicago,
new jersey

我试过了:

details.sort((a, b)=> a.place - b.place)).map((data) => {
return(
 <div>
   <li>{data.place}</li>
 </div>
)})

2 个答案:

答案 0 :(得分:0)

对于基于其他Array的排序数组,您可以使用此代码

&#13;
&#13;
var details = [{
    "name": "john",
    "place": "new york"
}, {
    "name": "mark",
    "place": "chicago"
}, {
    "name": "tom",
    "place": "san jose"
}, {
    "name": "dansk",
    "place": "new jersey"
}];

var sortingArray = ["san jose", "new york", "chicago", "new jersey"];


var result = [];



sortingArray.forEach(function (key) {
    var found = false;
    details = details.filter(function (item) {
        if (!found && item.place == key) {
            result.push(item);
            found = true;
            return false;
        } else
            return true;
    })
})

console.log(result);
&#13;
&#13;
&#13;

重新排列数组后,您可以映射

result.map((data) => {
   return (
       <div>
           <li>{data.place}</li>
       </div>
   )
})

答案 1 :(得分:0)

我在这些项目的排序顺序中没有看到任何逻辑,因此我选择了一个定义排序顺序的列表。

&#13;
&#13;
let order = ["san jose", "new york", "chicago", "new jersey"];

var details = [{
    "name": "john",
    "place": "new york"
  },
  {
    "name": "mark",
    "place": "chicago"
  },
  {
    "name": "tom",
    "place": "san jose"
  },
  {
    "name": "dansk",
    "place": "new jersey"
  }]
  .sort((a,b) => order.indexOf(a.place) - order.indexOf(b.place));
  
console.log(details);
&#13;
&#13;
&#13;