简体   繁体   English

Map 对象数组的嵌套

[英]Map the nesting of array of objects

I have this data:我有这个数据:

const data = [
  {
    name: 'chase',
    advisors: [
      {
        name: 'mark',
        clients: [
          { name: 'carol', savings: 500, checking: 600 },
          { name: 'toby', savings: 500, checking: 300 },
          { name: 'nich' }
        ]
      },
      {
        name: 'holly',
        clients: [
          { name: 'john', savings: 900 },
          { name: 'jim', checking: 200 },
          { name: 'bruce', checking: 200 },
          { name: 'sarah', savings: 500, checking: 300 }
        ]
      }
    ]
  },
  {
    name: 'citiBank',
    advisors: [
      {
        name: 'cindy',
        clients: [ { name: 'casey', savings: 500, checking: 200 } ]
      },
      { name: 'bob', clients: null }
    ]
  },
  { name: 'hsbc', advisors: null }
];

The output we have to get is an array of objects with that are ordered by greatest value of savings first, and if the savings value is the same, we have to order by the greatest checking value first.我们要得到的 output 是一个对象数组,按照储蓄值的最大值排序,如果储蓄值相同,就按照校验值的最大值排序。

Finally, the client array should look like this:最后,客户端数组应该如下所示:

[{ name: 'john', savings: 900, firm:'chase',advisor:'holly' },{ name: 'carol', savings: 500, checking: 600, firm: 'chase', advisor: 'mark'},{ name: 'sarah', savings: 500, checking: 300 ,advisor:'holly',firm:'chase'},{ name: 'toby', savings: 500, checking: 300, firm:'chase',advisor:'mark', },{ name: 'casey', savings: 500, checking: 200,firm:'citi bank',advisor:'cindy' }....]

Below is the function defined下面是定义的function

const maxSavingsData = ()=>{
  const client = [];
  console.log(client);
}
maxSavingsData(data);

I would split this task into two phases:我会将此任务分为两个阶段:

  1. First create the target objects in the order you get them from the source data;首先按照从源数据中获取目标对象的顺序创建目标对象;
  2. Sort that array using the sort callback function.使用sort回调 function 对该数组进行排序。

Here is how that could work:这是如何工作的:

 const maxSavingsData = (data) => data.flatMap(({name: firm, advisors}) => (advisors?? []).flatMap(({name: advisor, clients}) => (clients?? []).map(client => ({...client, firm, advisor})) ) ).sort((a, b) => (b.savings?? 0) - (a.savings?? 0) || (b.checking?? 0) - (a.checking?? 0) ); const data = [{name: 'chase',advisors: [{name: 'mark',clients: [{ name: 'carol', savings: 500, checking: 600 },{ name: 'toby', savings: 500, checking: 300 },{ name: 'nich' }]},{name: 'holly',clients: [{ name: 'john', savings: 900 },{ name: 'jim', checking: 200 },{ name: 'bruce', checking: 200 },{ name: 'sarah', savings: 500, checking: 300 }]}]},{name: 'citiBank',advisors: [{name: 'cindy',clients: [ { name: 'casey', savings: 500, checking: 200 } ]},{ name: 'bob', clients: null }]},{ name: 'hsbc', advisors: null }]; const clients = maxSavingsData(data); console.log(clients);

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

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