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

我有一个表格模式数组对象,如下所示,直到 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 级列对象进行分组。谢谢


慕森卡
浏览 103回答 2
2回答

翻过高山走不出你

您可以通过避免不需要的循环属性来对数据进行分组。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; }

慕标琳琳

你可以写你的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 }              )        )  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript