1 回答
TA贡献1735条经验 获得超5个赞
您可以使用reduce()方法来做到这一点。
var items = [{ item: { name: "cap", id: "5d767e1358ad1d0ca4894592", price: 50, vendorid: "5d72d2a6d87c4628ba60e046" } } ,{ item: { name: "shorts", price: 100, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "shoes", price: 90, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "black hood", price: 120, vendorid: "5d71c51f2092d318a1bf8f53" } } ];
let result = items.reduce((obj, currentValue) => {
if (!obj[currentValue.item.vendorid]) {
obj[currentValue.item.vendorid] = [];
}
obj[currentValue.item.vendorid].push({
...currentValue.item
});
return obj;
}, {});
const orderedResult = {};
// Sorting on vendorid.
Object.keys(result).sort().forEach(key => orderedResult[key] = result[key]);
console.log(orderedResult);
关于对象属性排序的说明:
从 ECMAScript 2015 (ES6) 开始,对象自身的属性对于某些操作确实具有顺序,但依赖它并不是一个好主意。如果顺序很重要,那么最好使用数组或类似的东西。
添加回答
举报