我正在尝试通过查看另一个数组的顺序对对象数组进行排序,我的第一个数组就是这样
["HV001O3XL", "HV001OSML", "HV001OLGE"]
我的对象数组就像:
[{productcode: "HV001OSML", price: 6, qty: "2", desc: "HV001 WAISTCOAT ORN", stock: "138"},{productcode: "HV001OLGE", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "271"},{productcode: "HV001O3XL", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "1112"}]
我想重新调整对象数组的位置,以便使object.productcode与第一个数组匹配,其中HV001O3XL优先于HV001OSML等。
答案 0 :(得分:4)
const objs = [
{
productcode: "HV001OSML",
price: 6,
qty: "2",
desc: "HV001 WAISTCOAT ORN",
stock: "138"
},
{
productcode: "HV001OLGE",
price: 6,
qty: "1",
desc: "HV001 WAISTCOAT ORN",
stock: "271"
},
{
productcode: "HV001O3XL",
price: 6,
qty: "1",
desc: "HV001 WAISTCOAT ORN",
stock: "1112"
}
];
const result = [
"HV001O3XL",
"HV001OSML",
"HV001OLGE"
].map((key) => objs.find(item => item.productcode === key));
console.log(result);
答案 1 :(得分:1)
const orders = ['a', 'b', 'c', 'd'];
let objects = [{
code: 'd'
}, {
code: 'c'
}, {
code: 'a',
}, {
code: 'b'
}]
objects.sort((a, b) => orders.indexOf(a.code) - orders.indexOf(b.code));
console.log(objects);