用Javascript创建一个嵌套数组

问题描述 投票:0回答:1

有什么建议,如何从下面的对象数组中得到嵌套数组对象?

[
{COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "S"}
{COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "L"}
{COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "S"}
{COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "M"}
{COLOR: "Red", FABRIC_DESIGN: "Velvet", SIZE: "S"}
]

我想得到的是。

[
      {
        label: "Black",
        children: [
          { label: "Leather", children: [{ label: "S" }, { label: "L" }] },

          { label: "Velvet", children: [{ label: "S" }, { label: "M" }] }
        ]
      },

      {
        label: "Red",
        children: [{ label: "Velvet", children: [{ label: "S" }] }]
      }
];

我设法为有2个属性的对象做了嵌套,但不超过2个属性 我不知道如何为有N个属性的对象做嵌套。

javascript arrays multidimensional-array
1个回答
1
投票

你可以使用 reduceforEach 方法和一个对象来保存每个层次的数据。

const data = [{COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "S"},{COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "L"},{COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "S"},{COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "M"},{COLOR: "Red", FABRIC_DESIGN: "Velvet", SIZE: "S"}]

const result = []
const levels = {result}
const keys = ['COLOR', 'FABRIC_DESIGN', 'SIZE']

data.forEach(o => {
  keys.reduce((r, k, i, a) => {
    const label = o[k];

    if (!r[label]) {
      const value = {label}

      if (a[i + 1]) {
        r[label] = {result: []}
        value.children = r[label].result
      }

      r.result.push(value)
    }

    return r[label]
  }, levels)
})

console.log(result)

0
投票

EDIT : 现在,你可以指定层次结构了。

var data = [
  {COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "S"},
  {COLOR: "Black", FABRIC_DESIGN: "Leather", SIZE: "L"},
  {COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "S"},
  {COLOR: "Black", FABRIC_DESIGN: "Velvet", SIZE: "M"},
  {COLOR: "Red", FABRIC_DESIGN: "Velvet", SIZE: "S"}
]
var hierarchy = ['COLOR', 'FABRIC_DESIGN', 'SIZE'];

// temporary object to make uniqu entries
var structuredDatas = {};

data.forEach(el => {
  var editedDatas = structuredDatas;
  for (depth of hierarchy) {
    if (typeof el[depth] === 'undefined') {
      break;
    }
    if (!editedDatas[el[depth]]) {
      editedDatas[el[depth]] = { label: el[depth], children: {} };
    }
    editedDatas = editedDatas[el[depth]].children;
  }
});
// all data are structured

// next, we format data as expected
var formattedDatas = Object.values(structuredDatas).map(formatLevel)

function formatLevel(datas) {
  datas.children = Object.values(datas.children).map(formatLevel)
  return datas
}
console.log(JSON.stringify(formattedDatas, null, 2));
© www.soinside.com 2019 - 2024. All rights reserved.