[英]How to get deeply nested object structure from array of values with Javascript
[英]Javascript - How to sort values in a nested object, based on a number deeply nested?
我有一個包含國家,城市和那些城市中商店的對象。 我想顯示(以后)的國家/地區,根據該國家/地區的城市數量排序(有效)(我的代碼),然后我想根據商店的數量對城市進行排序(因此,商店數量最多的城市排在第一位)。 我已經嘗試了很長時間,只是無法使它正常工作,因為無論我嘗試或做的任何事情都不起作用。 我需要訪問“ shopNum”屬性,然后訪問城市並進行排序,但我沒有做過/做過的工作。 任何幫助都將非常棒。 抱歉,如果它看起來可能太基礎了,但是我嘗試了一段時間,進行了研究等,有點迷失了。
var data = {
Italy: {
cityNum: 2,
Rome: {
shops: ['Shop123', 'shopxyz'],
shopNum: 2
},
Milan: {
shops: ['Shop1', 'shopA', 'shopD'],
shopNum: 3
}
},
USA: {
cityNum: 1,
Chicago: {
shops: ['Shop123', 'shopxyz', 'shopZ'],
shopNum: 3
},
},
}
var sortedCountries = Object.keys(data).sort((a, b) => {
return data[b]["cityNum"] - data[a]["cityNum"];
}) //works fine
var sortedShops = Object.values(data).map(x => {
Object.values(Object.keys(x).map(item => {
if (item !== "cityNum") {
console.log(item)
return item;
}
})).map(x => console.log("item x", x))
})
sortedCities
普通對象不是依賴某些屬性順序的正確結構。 如果要對那些對象進行排序,則應改用數組。 有關更多信息,請參見此問答 。
因此,您的目標數據結構將有所不同。 同時,您可以取消使用cityNum
和shopNum
屬性,因為一旦有了數組(它們具有length
屬性),它們就變得多余了。
我將由內而外地工作,開始創建帶有城市的排序數組,然后最后根據城市數量對那些子結構進行排序:
var data = {Italy: {cityNum: 2,Rome: {shops: ['Shop123', 'shopxyz'],shopNum: 2},Milan: {shops: ['Shop1', 'shopA', 'shopD'],shopNum: 3}},USA: {cityNum: 1,Chicago: {shops: ['Shop123', 'shopxyz', 'shopZ'],shopNum: 3},},} var sortedCountries = Object.entries(data) .map(([country, cities]) => ({ country, cities: Object.keys(cities) .filter(prop => prop !== "cityNum") .sort((a, b) => cities[b].shops.length - cities[a].shops.length) .map(city => ({ city, shops: cities[city].shops })) })) .sort((a, b) => b.cities.length - a.cities.length) console.log(sortedCountries);
你可以建立一個新的對象調用allCities
用.reduce
包含所有的城市。 然后使用與cityNum
相同的排序函數,但這次將其應用於allCities
和屬性shopNum
。
這是代碼:
const data={Italy:{cityNum:2,Rome:{shops:["Shop123","shopxyz"],shopNum:2},Milan:{shops:["Shop1","shopA","shopD"],shopNum:3}},USA:{cityNum:1,Chicago:{shops:["Shop123","shopxyz","shopZ"],shopNum:3}}}; const sortedCountries = Object.keys(data).sort((a, b) => { return data[b]["cityNum"] - data[a]["cityNum"]; }); const allShops = Object.values(data).reduce((allCities, country) => { // extract the cityNum from the country object, the rest are cities const { cityNum, ...cities } = country; // return an object containing all cities + the cities from the current country return { ...allCities, ...cities }; }, {}); const sortedShops = Object.keys(allShops).sort((a, b) => { return allShops[b]["shopNum"] - allShops[a]["shopNum"]; }); console.log(sortedCountries) console.log(sortedShops);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.