繁体   English   中英

Javascript - 对对象的多个对象数组进行排序

[英]Javascript - sort an array of multiple objects of objects

我尝试对对象的多个对象数组进行排序但没有成功。

这是我的数据库:

 var jsonDatas = [ { "type": "Voiture", "items": [ { "name": "Fiat Punto", "description": "Je suis une voiture", "price": 10000, "quantity": 2, }, { "name": "Porsche 911", "description": "Je suis une belle voiture", "price": 80000, "quantity": 0, }, ], }, { "type": "Maison", "items": [ { "name": "Villa sur la plage", "description": "Quelle belle vue", "price": 870000, "quantity": 1, }, { "name": "Maison à la campagne", "description": "Vive le calme", "price": 170000, "quantity": 3, } ], }
我希望我的数据按项目名称(字母顺序)排序:获得菲亚特、梅森、保时捷、别墅,问题是类型,因为它首先排序类型然后是产品

在此处输入图像描述

我试过这个例如:

 function sortDatasASC(){ database.forEach(element => element.items.sort((a, b) => (a.name > b.name)? 1: -1)), catalogFiltered();

我试图创建一个中间数组来推送项目,然后与类型重新关联,但它不起作用。

例如,这适用于一个复选框,如果有库存则显示产品,但不能复制它进行排序

 const choiceStock = document.getElementById('stockCheck').addEventListener('change', function () { let datas = []; if (this.checked) { let filter = []; database.forEach(element => filter.push({ 'type': element.type, 'items': element.items.filter(test => test.quantity > 0) }) ); datas = filter; } else { datas = database; } showCatalog(datas); });

如果你有什么想法??

提前致谢。

您的数据按类型分组,但由于您希望它按名称而不是按类型/名称排序,我会将结构展平为一个对象数组,然后应用上面的逻辑:

const flattened = jsonDatas.reduce((acc, entry) => {
  //since we dont want to lose the type information I'm cloning
  //each item and adding a type property to it.
  const items = entry.items.map(i => ({ ...i, type: entry.type }));
  return acc.concat(items);
}, []);

flattened.sort((a, b) => {
  if (a.name.toLowerCase() === b.name.toLowerCase()) {
    return 0;
  }
  return a.name.toLowerCase() > b.name.toLowerCase() ? -1 : 1;
});

//the type is retained so we can rebuild the structure:
const restructured = flattened.map(item => ({
  type: item.type,
  items: [item],
}));

console.log(flattened);
console.log(restructured);

我还假设您想要不区分大小写的排序。 如果不是这种情况,请拨打 go 并删除“toLowerCase”调用。

首先,您需要制作一个平面阵列。 为了能够按type属性排序,您需要将type添加到每个元素。 您还可以根据属性类型(字符串/数字)更改排序 function。 这只是一个简单的例子::

 const jsonDatas=[{type:"Voiture",items:[{name:"Fiat Punto",description:"Je suis une voiture",price:1e4,quantity:2},{name:"Porsche 911",description:"Je suis une belle voiture",price:8e4,quantity:0}]},{type:"Maison",items:[{name:"Villa sur la plage",description:"Quelle belle vue",price:87e4,quantity:1},{name:"Maison à la campagne",description:"Vive le calme",price:17e4,quantity:3}]}]; const flatData = jsonDatas.flatMap(({ items, type }) => items.map(item => ({...item, type }))); const sortBy = (arr, property, direction = 'asc') => { if (arr.length === 0) return []; const propertyType = typeof arr.at(0)[property]; const sortCallbacks = { string: (e1, e2) => e1[property].localeCompare(e2[property]), number: (e1, e2) => e1[property] - e2[property], }; const sortedAsc = arr.sort(sortCallbacks[propertyType]); if (direction === 'asc' ) return sortedAsc; return sortedAsc.reverse(); }; console.log(sortBy(flatData, 'name' )); console.log(sortBy(flatData, 'type', 'dsc')); console.log(sortBy(flatData, 'price', 'dsc'));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

我终于找到了解决方案,看看下面是否对你们中的一些人有帮助:

 function createArrayToSort(database) { let datas = []; database.forEach(element => element.items.forEach(items => datas.push({'type': element.type, 'items': [items]}) )) return datas; }; function sortByName(direction){ let datas = createArrayToSort(database); if(direction == "ASC") { datas.sort((a, b) => (a.items[0].name > b.items[0].name)? 1: -1); } else { datas.sort((a, b) => (b.items[0].name > a.items[0].name)? 1: -1); } showCatalog(datas); }; function sortByPrice(direction){ let datas = createArrayToSort(database); if(direction == "ASC") { datas.sort((a, b) => (a.items[0].price > b.items[0].price)? 1: -1); } else { datas.sort((a, b) => (b.items[0].price > a.items[0].price)? 1: -1); } showCatalog(datas); }; const nameASC = document.getElementById('nameASC').addEventListener('click', function () { sortByName('ASC') });

您在问题片段中显示的jsonDatas定义与显示其他值的屏幕截图不匹配(例如标致 205作为"type": "Voiture"条目)。 Peugeot 205值的存在表示完整的jsonDatas数组包含除您列出的对象之外的其他相同类型的对象( VoitureMaison )。

如果那是jsonDatas的结构方式,那么要根据需要对其进行排序,您需要做两件事:

  1. 第一:将jsonDatas转换为一个对象数组,例如那些对象包含一个只有一个元素的items数组。 这将使您可以单独管理记录的顺序。 在我下面的代码片段中,这将是singleItem数组中的结果。

  2. 第二:在将输入转换为singleItem样式数组后,您可以简单地按items数组中唯一项目的名称对该数组进行排序(即: .items[0].name )。

您可以在下面看到工作代码。 我使用了flatMapmap ,因为这些是进行步骤 #1 转换的便捷方法。

 var jsonDatas = [ { "type": "Voiture", "items": [ { "name": "Fiat Punto", "description": "Je suis une voiture", "price": 10000, "quantity": 2, }, { "name": "Porsche 911", "description": "Je suis une belle voiture", "price": 80000, "quantity": 0, }, ], }, { "type": "Maison", "items": [ { "name": "Villa sur la plage", "description": "Quelle belle vue", "price": 870000, "quantity": 1, }, { "name": "Maison à la campagne", "description": "Vive le calme", "price": 170000, "quantity": 3, } ], } ] var singleItem = jsonDatas.flatMap(t => t.items.map(i => { return { type: t.type, items: [ i ] } })) var sorted = singleItem.sort((a, b) => a.items[0].name.localeCompare(b.items[0].name)) console.log(sorted)

对于通过类型进行简单排序就像是

jsonDatas.sort((a, b) => (a.type > b.type)? 1: -1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM