借助此篇博客,实现了需要的功能,特此记录一下:https://www.cnblogs.com/guojbing/p/10872867.html
假设有一个对象数组:
const arr1 = [
{buyerId: "1", name: "WW"},
{buyerId: "2", name: "RR"},
{buyerId: "3", name: "OO"},
{buyerId: "4", name: "ll"},
{buyerId: "5", name: "DD"},
{buyerId: "6", name: "SS"}
]
另一对象数组为:
const arr2 = [
{buyerId: "4", totalPrice: "7.00"},
{buyerId: "3", totalPrice: "90.00"},
{buyerId: "2", totalPrice: "10.00"},
{buyerId: "6", totalPrice: "70.00"},
{buyerId: "1", totalPrice: "9.00"},
{buyerId: "5", totalPrice: "60.00"}
]
现在希望arr2按照arr的buyerId属性排序,并显示其价格。应该怎么做呢?
首先,提取出arr1中的buyerId到一个新的数组:
let curArr = [];
arr1.find(item => {
curArr.push(item.buyerId)
});
这样就获取到了数组:
接着,让arr2按照curArr的数据排放顺序排列:
let newArr = [];
arr2.sort((a, b) => {
const prev = curArr.indexOf(a.buyerId);
const next = curArr.indexOf(b.buyerId);
return prev-next;
});
arr2.forEach(item => {
newArr.push(item)
})
得到的结果为:
这样就得到了按照要求排列的新数组,如果要只显示价格,就把newArr数组中的totalPrice提取到新的数组中,即可显示。
以上,就是我想要分享给大家的,还有另一种简单点的,对象数组根据数组进行比较的排序方式,具体的请看文章开始贴出的博客地址。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。