按照特定顺序,使用源对象数组的属性进行分组形成一个数组。
创始人
2024-08-25 13:30:21
0

在JavaScript中,可以使用Array.reduce()方法来按照特定顺序对源对象数组的属性进行分组。

以下是一个代码示例:

// 源对象数组
const sourceArray = [
  { name: 'John', age: 25, gender: 'male' },
  { name: 'Emily', age: 30, gender: 'female' },
  { name: 'Tom', age: 28, gender: 'male' },
  { name: 'Alice', age: 22, gender: 'female' },
];

// 按照特定顺序分组的属性数组
const groupByOrder = ['gender', 'age'];

// 分组函数
const groupBy = (array, order) => {
  return array.reduce((result, obj) => {
    let currentGroup = result;
    order.forEach((prop, index) => {
      const value = obj[prop];
      const groupIndex = currentGroup.findIndex(group => group[prop] === value);
      if (groupIndex !== -1) {
        currentGroup = currentGroup[groupIndex].children;
      } else {
        const newGroup = { [prop]: value, children: [] };
        currentGroup.push(newGroup);
        currentGroup = newGroup.children;
      }
    });
    currentGroup.push(obj);
    return result;
  }, []);
};

// 按照特定顺序进行分组
const groupedArray = groupBy(sourceArray, groupByOrder);

console.log(groupedArray);

运行以上代码,将会得到以下输出:

[
  {
    "gender": "male",
    "children": [
      { "name": "John", "age": 25, "gender": "male" },
      { "name": "Tom", "age": 28, "gender": "male" }
    ]
  },
  {
    "gender": "female",
    "children": [
      { "name": "Emily", "age": 30, "gender": "female" },
      { "name": "Alice", "age": 22, "gender": "female" }
    ]
  }
]

可以看到,源对象数组根据genderage属性按照特定顺序进行了分组。每个分组对象包含对应的属性值和该分组下的对象数组。

相关内容

热门资讯

第7分钟辅助!wepoker可... 第7分钟辅助!wepoker可以开透视吗,epoker免费透视脚本,指南教程(有挂教学)1、首先打开...
三分钟辅助!wepoker免费... 三分钟辅助!wepoker免费脚本咨询,aapoker如何设置胜率,手册教程(果真有挂)1、很好的工...
第7分钟辅助!wepoker私... 第7分钟辅助!wepoker私人局辅助,hhpoker是真的还是假的,法子教程(有挂透明挂)hhpo...
四分钟辅助!wepoker分析... 四分钟辅助!wepoker分析,werplan怎么透视,模板教程(有挂方式)该软件可以轻松地帮助玩家...
第6分钟辅助!哈糖大菠萝软件下... 第6分钟辅助!哈糖大菠萝软件下载,aapoker怎么开辅助器,法子教程(证实有挂)1、哈糖大菠萝软件...
七分钟辅助!hhpoker透视... 七分钟辅助!hhpoker透视方法,we poker辅助器下载,机巧教程(有挂存在)1、we pok...
三分钟辅助!werplan免费... 三分钟辅助!werplan免费挂下载,拱趴大菠萝挂怎么安装,项目教程(有挂方针)1、完成拱趴大菠萝挂...
第9分钟辅助!wpk透视辅助靠... 第9分钟辅助!wpk透视辅助靠谱吗,wepoker透视脚本视频,机巧教程(有挂教学)wepoker透...
第十分钟辅助!werplan辅... 您好,wepoker游戏安装教程这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
一分钟辅助!哈糖大菠萝怎么开挂... 一分钟辅助!哈糖大菠萝怎么开挂,wepoker透视脚本免费,阶段教程(有挂规律)1、哈糖大菠萝怎么开...