我有一個專案,我收到一份產品清單,然后按制造商分組。我想以編程方式在頁面上顯示這些,但需要按照產品從多到少的順序進行。我需要想出一種演算法來將物件鍵從大多數產品排序到最少產品。
這是我所擁有的以及我需要到達的地方的簡化示例:
let devices = {
Sony: [
{name: 'Experia 1', productCode: 's1'},
{name: 'Experia 2', productCode: 's2'}
],
Apple: [
{name: 'iPhone 8', productCode: 'a1'},
{name: 'iPhone 9', productCode: 'a2'},
{name: 'iPhone 10', productCode: 'a3'},
{name: 'iPhone 11', productCode: 'a4'}
],
Huawei : [
{name: 'S 21', productCode: 'h1'}
],
LG: [
{name: 'V60', productCode: 'l1'},
{name: 'V60 Ultra', productCode: 'l2'},
{name: 'G7', productCode: 'l3'}
]
}
我需要訂購資料,因此它從最多的制造商開始,然后下降到最少的制造商。所以需要修改成這樣:
{
Apple: [
{name: 'iPhone 8', productCode: 'a1'},
{name: 'iPhone 9', productCode: 'a2'},
{name: 'iPhone 10', productCode: 'a3'},
{name: 'iPhone 11', productCode: 'a4'}
],
LG: [
{name: 'V60', productCode: 'l1'},
{name: 'V60 Ultra', productCode: 'l2'},
{name: 'G7', productCode: 'l3'}
]
Sony: [
{name: 'Experia 1', productCode: 's1'},
{name: 'Experia 2', productCode: 's2'}
],
Huawei : [
{name: 'S 21', productCode: 'h1'}
],
}
提供的設備經常會有所不同,因此每次用戶訪問頁面時我都需要對這些資料進行排序。因此,我正在尋找最短的語法來實作這一點。
I am finding tutorials on how to sort object keys alphabetically, and other similarly related algorithms, but not one that does exactly this. I've started trying to customize some basic sorting algorithms, but data manipulation is not my strong suit, so they are either failing or turning into a bloated spaghetti code mess.
Is there a short and easy way to convert the data as described? Perhaps there is a sorting method or design pattern that is particularly well suited to the task. I've been looking into lodash commands, but am not finding anything that immediately jumps out as a solution.
I'd be very grateful for any advice that anyone could offer. Thank you in advance
uj5u.com熱心網友回復:
您可以將其轉換為陣列,按長度對其進行排序,然后將其轉換回物件。
let devices = {
Sony: [
{name: 'Experia 1', productCode: 's1'},
{name: 'Experia 2', productCode: 's2'}
],
Apple: [
{name: 'iPhone 8', productCode: 'a1'},
{name: 'iPhone 9', productCode: 'a2'},
{name: 'iPhone 10', productCode: 'a3'},
{name: 'iPhone 11', productCode: 'a4'}
],
Huawei : [
{name: 'S 21', productCode: 'h1'}
],
LG: [
{name: 'V60', productCode: 'l1'},
{name: 'V60 Ultra', productCode: 'l2'},
{name: 'G7', productCode: 'l3'}
]
}
devices = Object.fromEntries(Object.entries(devices).sort( (a,b) => b[1].length - a[1].length));
console.log(devices)
如果您在物件上回圈,我不會將其轉換回物件,我只會使用Object.entries并基于此輸出我的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441060.html
