【问题标题】:How I can count values and obtain another array structure?我如何计算值并获得另一个数组结构?
【发布时间】:2022-01-06 04:00:35
【问题描述】:

我有一个对象数组,我想将它们转换为使用图表中的数据。有人推荐使用 lodash,但我不想使用任何库。所以这里是数组的例子:

const items = [
      {
        priceChangeType: 'CL',
        hierarchy: {
          department: {
            description: 'TEXTILES',
          },
        },
      },
      {
        priceChangeType: 'PM',
        hierarchy: {
          department: {
            description: 'CLOTHES',
          },
        },
      },
      {
        priceChangeType: 'CL',
        hierarchy: {
          department: {
            description: 'TEXTILES',
          },
        },
      },
      {
        priceChangeType: 'CL',
        hierarchy: {
          department: {
            description: 'CLOTHES',
          },
        },
      },
  {
        priceChangeType: 'PM',
        hierarchy: {
          department: {
            description: 'BATH',
          },
        },
      },
  {
        priceChangeType: 'PM',
        hierarchy: {
          department: {
            description: 'TOOLS',
          },
        },
      },
    {
        priceChangeType: 'CL',
        hierarchy: {
          department: {
            description: 'TOOLS',
          },
        },
      },
   {
        priceChangeType: 'CL',
        hierarchy: {
          department: {
            description: 'TOOLS',
          },
        },
      },
    ]

我想要这样的输出,这是图表所需的格式。

const data = [
  {name: 'TOOLS', PM: 1, CL: 2},
  {name: 'CLOTHES', PM: 1, CL: 1},
  {name: 'TEXTILES', PM: 0, CL: 2},
  {name: 'BATH', PM: 1, CL: 0},
]

这是我来的最远的,但只是总数。

const totalPriceChangesType = Object.entries(items.reduce((r, v, i, a, k = v.priceChangeType) => ((r[k] || (r[k] = [])).push(v), r), {})).map(
    ([key, value]) => ({
      [key] : value.length,
    }),
  )

【问题讨论】:

    标签: javascript arrays json object


    【解决方案1】:

    您可以通过将数组映射到[priceChangeType, 0] 对并使用Object.fromEntries() 来创建初始化为0 的所有priceChangeType 的对象(priceChangeTypes)。

    然后将原始数组缩减为一个 Map。对于每个新的hierarchy.department.description,通过将priceChangeTypes 传播到一个新对象,在地图中创建一个条目,并增加相关的priceChangeType

    使用Array.from() 转换回数组。

    const items = [{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'BATH'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}}]
    
    // Create an initialized counts object = { CL: 0, PM: 0 }
    const priceChangeTypes = Object.fromEntries(items.map(o => [o.priceChangeType, 0]))
    
    const result = Array.from(
      items.reduce((acc, o) => {
        const key = o.hierarchy.department.description
        
        // initialize the object for the current key if needed
        if(!acc.has(key)) acc.set(key, { ...priceChangeTypes })
        
        // increment the relevant priceChangeType
        acc.get(key)[o.priceChangeType] += 1
        
        return acc
      }, new Map()),
      ([names, values]) => ({ name, ...values }) // convert to an array
    )
    
    console.log(result)

    【讨论】:

      【解决方案2】:

      也许这个例子对你有帮助?

      const items = [{
          priceChangeType: "CL",
          hierarchy: {
            department: {
              description: "TEXTILES"
            }
          }
        },
        {
          priceChangeType: "PM",
          hierarchy: {
            department: {
              description: "CLOTHES"
            }
          }
        },
        {
          priceChangeType: "CL",
          hierarchy: {
            department: {
              description: "TEXTILES"
            }
          }
        },
        {
          priceChangeType: "CL",
          hierarchy: {
            department: {
              description: "CLOTHES"
            }
          }
        },
        {
          priceChangeType: "PM",
          hierarchy: {
            department: {
              description: "BATH"
            }
          }
        },
        {
          priceChangeType: "PM",
          hierarchy: {
            department: {
              description: "TOOLS"
            }
          }
        },
        {
          priceChangeType: "CL",
          hierarchy: {
            department: {
              description: "TOOLS"
            }
          }
        },
        {
          priceChangeType: "CL",
          hierarchy: {
            department: {
              description: "TOOLS"
            }
          }
        }
      ];
      
      // collect all possible PM, CL, etc. (example: {PM:0, CL:0})
      const priceChangeTypes = items.reduce((acc, item) => (acc[item.priceChangeType] = 0, acc), {});
      
      const total = Object.values(items.reduce((acc, item) => {
        const descriprion = item.hierarchy.department.description;
        const priceChangeType = item.priceChangeType;
        // create a new base object {name: "{description}", PM:0, CL:0, ...}
        if (!acc[descriprion]) acc[descriprion] = {
          name: descriprion,
          ...priceChangeTypes
        };
        acc[descriprion][priceChangeType]++;
        return acc;
      }, {}));
      
      console.log(total);

      【讨论】:

        【解决方案3】:

        逻辑

        • 使用Array.mapSetitems 数组生成唯一类型
        • 根据名称和类型减少 items 数组
        • 将缺少的类型添加到output 数组中的各个节点

        const items = [{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TEXTILES'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'CLOTHES'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'BATH'}}},{priceChangeType: 'PM',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}},{priceChangeType: 'CL',hierarchy: {department: {description: 'TOOLS'}}}];
        // Generate unique types
        const types = Array.from(new Set(items.map(item => item.priceChangeType)));
        
        // Reduce the items array against the name and type
        const output = items.reduce((acc, curr, index, array, name = curr.hierarchy.department.description, type = curr.priceChangeType) => {
            acc[name] = acc[name] || {};
            acc[name][type] = ++acc[name][type] || 1;
            return acc;
        }, {});
        
        // Add the missing type to each object in output
        Object.entries(output).forEach(([key, value]) => types.forEach(type => output[key][type] = output[key][type] || 0))
        console.log(output);

        【讨论】:

          猜你喜欢
          • 2022-06-28
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 2021-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多