为了账号安全,请及时绑定邮箱和手机立即绑定

对具有嵌套级别的对象数组进行分组

对具有嵌套级别的对象数组进行分组

慕森卡 2023-04-14 15:14:51
我有一个表格模式数组对象,如下所示,直到 n 级。它可以是任何父母孩子的记录var records = [  { country: "USA", state: "FLORIDA", city: "city1" },  { country: "USA", state: "FLORIDA", city: "city2" },  { country: "USA", state: "FLORIDA", city:"city3" },  { country: "USA", state: "ALASKA" },  { country: "USA", state: "ALBAMA" },]var columns = ["country","state","city"]  // upto n column我需要按以下格式对第 n 级进行分组,因为可以有 n 级关系,按以下格式对记录进行分组{  sequencer: 1, value: 'USA', loop: [    { sequencer: 1, value: 'FLORIDA', loop: [      { sequencer: 1, value: 'city1' },      { sequencer: 2, value: 'city2' },      { sequencer: 3, value: 'city3' },    ], },    { sequencer: 2, value: 'ALASKA' },    { sequencer: 3, value: 'ALBAMA' },  ],}有人可以编写一个递归函数来对 n 级列对象进行分组。谢谢
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

您可以通过避免不需要的循环属性来对数据进行分组。


const

    data = [{ country: "USA", state: "FLORIDA", city: "city1" }, { country: "USA", state: "FLORIDA", city: "city2" }, { country: "USA", state: "FLORIDA", city: "city3" }, { country: "USA", state: "ALASKA" }, { country: "USA", state: "ALBAMA" }],

    keys = ['country', 'state', 'city'],

    result = data.reduce((loop, o) => {

        keys

            .map(k => o[k])

            .filter(Boolean)

            .reduce((r, value) => {

                let temp = (r.loop ??= []).find(q => q.value === value);

                if (!temp) r.loop.push(temp = { sequence: r.loop.length + 1, value });

                return temp;

            }, { loop });

        return loop;

    }, []);


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反对 回复 2023-04-14
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

你可以写你的transform使用flatMap和递归 -

const transform = ([ name, ...more ], { value, loop = [{}] }, r = {}) =>

  name === undefined

    ? [ r ]

    : loop.flatMap(t => transform(more, t, { [name]: value, ...r }))


const records =

  {sequencer:1,value:'USA',loop:[{sequencer:1,value:'FLORIDA',loop:[{sequencer:1,value:'city1'},{sequencer:2,value:'city2'},{sequencer:3,value:'city3'}]},{sequencer:2,value:'ALASKA'},{sequencer:3,value:'ALBAMA'}]}


const columns =

  ['country', 'state', 'city']


const result =

  transform(["country", "state", "city"], records)

  

console.log(JSON.stringify(result, null, 2))

function等同于上述表达式的语句=>-


function transform

  ( [ name, ...more ]

  , { value, loop = [{}] }

  , r = {}

  )

  { if (name === undefined)

      return [ r ]

    else 

      return loop.flatMap

        ( t =>

            transform

              ( more

              , t

              , { [name]: value, ...r }

              )

        )

  }



查看完整回答
反对 回复 2023-04-14
  • 2 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信