将平面数组简化为2级嵌套json对象数组

时间:2019-06-04 14:35:30

标签: javascript json nested reduce

我有以下平面数组:

{ "State": "New York", "Name": "Jane", "Product": "Apple" },
{ "State": "New York", "Name": "Jill", "Product": "Banana"},
{ "State": "California", "Name": "Jill", "Product": "Apple" },
{ "State": "California", "Name": "Jill", "Product": "Banana"}

是否可以创建2级嵌套数组(即,名称>嵌套状态数组>嵌套产品数组)?看起来如下:

{
  "Name": "Jill",
  "States": [
   {
   "State": "California",
   "Products": [
      {
    "Product": "Apple"
      },
      {
          "Product": "Banana"
      }
    ]
   },
   {
   "State": "New York",
   "Products": [
      {
          "Product": "Banana"
      }
    ]
   }
  ]
 },
 {
  "Name": "Jane",
  "States": [
   {
   "State": "New York",
   "Products": [
     {
      "Product": "Apple"
     }
    ]
   }
  ]
 }

我已经能够嵌套一个级别(状态)。您将如何嵌套第二层?

这是一个堆叠闪电战:https://stackblitz.com/edit/angular-lu6zj2

this.grouped_data = this.data.reduce((data, item) => {
  data[item.Name] = data[item.Name] || { Name: item.Name, States: []}
  data[item.Name].States.push(item) 
  return data;
}, {})

1 个答案:

答案 0 :(得分:2)

let data = [
  { "State": "New York", "Name": "Jane", "Product": "Apple" },
  { "State": "New York", "Name": "Jill", "Product": "Banana"},
  { "State": "California", "Name": "Jill", "Product": "Apple" },
  { "State": "California", "Name": "Jill", "Product": "Banana"}
];

let grouped = data.reduce((p, n) => {
  // Create the Lady
  if (!p[n.Name]) p[n.Name] = { States: [] };
  // Check if the state exists, if not create it, then push product into it
  if (!p[n.Name].States.some(state => state.State === n.State)) {
    p[n.Name].States.push({ State: n.State, Products: [n.Product] });
  } else {
    !p[n.Name].States.find(state => state.State === n.State).Products.push(n.Product);
  }
  return p;
}, {});

console.log(grouped);

此后,您还可以根据需要删除重复的产品。我让你处理!

编辑:我不尊重您的模型,我是个笨蛋……这是:

let data = [
  { "State": "New York", "Name": "Jane", "Product": "Apple" },
  { "State": "New York", "Name": "Jill", "Product": "Banana"},
  { "State": "California", "Name": "Jill", "Product": "Apple" },
  { "State": "California", "Name": "Jill", "Product": "Banana"}
];

let grouped = data.reduce((p, n) => {
  // Create the Lady
  if (!p.some(lady => lady.Name === n.Name)) p.push({ Name: n.Name, States: [] });
  let lady = p.find(lady => lady.Name === n.Name);
  // Check if the state exists, if not create it, then push product into it
  if (!lady.States.some(state => state.State === n.State)) {
    lady.States.push({ State: n.State, Products: [n.Product] });
  } else {
    lady.States.find(state => state.State === n.State).Products.push(n.Product);
  }
  return p;
}, []);

console.log(grouped);