javascript Map对象数组的嵌套

yjghlzjz  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(321)

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.
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

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

fumotvh31#

我将此任务分为两个阶段:
1.首先按照从源数据中获取目标对象的顺序创建目标对象;
1.使用sort回调函数对该数组进行排序。
以下是具体的操作方法:

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);

相关问题