【问题标题】:Creating index in JS array在 JS 数组中创建索引
【发布时间】:2021-09-09 16:21:55
【问题描述】:

我正在生成一个 mysql 查询,结果显示如下。

[

{ “品牌”:“品牌 1”, "channel": "TLP 频道", “备忘录”:449 }, { “品牌”:“品牌 1”, "channel": "C&C 频道", “备忘录”:10 }, { “品牌”:“品牌 1”, “频道”:“GT频道”, “备忘录”:1109 } ]

但我想准备如下结果数组:

[
{
    "Brand1" : [
        {
            "channel" : "TLP Channel",
            "Memo" : 449
        },
        {
            "channel" : "C&C Channel",
            "Memo" : 10
        },
        {
            "channel" : "GT Channel",
            "Memo" : 1109
        }
    ]
},
{
    "Brand2" : [
        {
            .....
        }
    ]
}

]

如何在 es6 中使用数组映射函数来准备这个?

【问题讨论】:

  • 包括你迄今为止尝试过的...
  • 提示:使用对象存储brand名称,其中值是数据数组,例如:map = { Brand1 => [], Brand2 => [] ...},然后仅通过查找键推送数据,例如:map[Brand1].push(<data>)

标签: javascript node.js arrays ecmascript-6


【解决方案1】:

您可以创建一个Map(),其中包含基于品牌的一系列商品。

然后您可以使用Array.prototype.map()Destructuring 和动态属性将您的地图转换为您想要的格式。

const currentFormat = [{
  "brand": "Brand 1",
  "channel": "TLP Channel",
  "memo": 449
}, {
  "brand": "Brand 1",
  "channel": "C&C Channel",
  "memo": 10
}, {
  "brand": "Brand 2",
  "channel": "GT Channel",
  "memo": 1109
}]

const itemsMap = new Map()

currentFormat.forEach(({
  brand,
  ...rest
}) => {
  if (itemsMap.has(brand)) itemsMap.get(brand).push(rest)
  else itemsMap.set(brand, [rest])
})

const newFormat = [...itemsMap].map(([brand, items]) => ({
  [brand]: items
}))

console.log(newFormat)

【讨论】:

    【解决方案2】:

    首先,让我先说存储此类数据的最佳方法是保持元素对象的键统一。现在,您希望以这样一种方式存储数据,即您的结果数组将对象作为元素,并且每个对象都有变量键。这不是好的做法。

    尝试做类似的事情

    {
       "name": "Brand1",
        "items" : [
            {
                "channel" : "TLP Channel",
                "Memo" : 449
            },
            {
                "channel" : "C&C Channel",
                "Memo" : 10
            },
            {
                "channel" : "GT Channel",
                "Memo" : 1109
            }
        ]
    }
    

    而不是

    {
        "Brand1" : [
            {
                "channel" : "TLP Channel",
                "Memo" : 449
            },
            {
                "channel" : "C&C Channel",
                "Memo" : 10
            },
            {
                "channel" : "GT Channel",
                "Memo" : 1109
            }
        ]
    }
    

    作为每个数组元素。除此之外,您的代码的解决方案也可以使用forEach() 来完成,而不仅仅是map()

    let result = [
      { brand: "Brand 1", channel: "TLP Channel", memo: 449 },
      { brand: "Brand 1", channel: "C&C Channel", memo: 10 },
      { brand: "Brand 1", channel: "GT Channel", memo: 1109 },
      
      { brand: "Brand 2", channel: "Something Channel", memo: 66 }
    ];
    
    let final = [];
    
    result.forEach(el => {    
      let i = final.findIndex(_obj => _obj.hasOwnProperty(el.brand));
    
      let _objToInsert = {
        channel: el.channel,
        memo: el.memo
      };
    
      if (i > -1) {
        // exists
        final[i][el.brand].push(_objToInsert);
      } else {
        // doesn't exist
        final.push({
          [el.brand]: [_objToInsert]
        });
      }
    });
    
    console.log(final)
    

    Find the working fiddle here

    【讨论】:

      【解决方案3】:

      您需要按brand 分组并将对象的其余部分作为值。

      1. 带有Map的解决方案

        const
            data = [{ brand: "Brand 1", channel: "TLP Channel", memo: 449 }, { brand: "Brand 1", channel: "C&C Channel", memo: 10 }, { brand: "Brand 1", channel: "GT Channel", memo: 1109 }],
            result = Array.from(
                data.reduce((m, { brand, ...o }) => m.set(brand, [...(m.get(brand) || []), o]), new Map),
                ([k, v]) => ({ [k]: v })
            );
        
        console.log(result);
        .as-console-wrapper { max-height: 100% !important; top: 0; }
      2. 带有用于分组的对象的解决方案

        const
            data = [{ brand: "Brand 1", channel: "TLP Channel", memo: 449 }, { brand: "Brand 1", channel: "C&C Channel", memo: 10 }, { brand: "Brand 1", channel: "GT Channel", memo: 1109 }],
            result = Object
                .entries(data.reduce((r, { brand, ...o }) => {
                    (r[brand] ??= []).push(o);
                    return r;
                }, {}))
                .map(([k, v]) => ({ [k]: v }))
        
        console.log(result);
        .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-12
        • 2017-10-15
        • 2021-12-18
        • 1970-01-01
        相关资源
        最近更新 更多