用JavaScript创建嵌套数组

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

关于如何从以下对象数组中获取嵌套数组/对象的任何建议?

[
{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
2个回答
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
投票

编辑:现在,您可以指定层次结构。

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.