【问题标题】:Parsing JSON and grouping multiple array values解析 JSON 并对多个数组值进行分组
【发布时间】:2021-04-07 02:52:52
【问题描述】:

我有一个如下所示的 JSON 响应

{
  data: [
    {
      attributes:[
        {
          type: 'size',
          value: '10'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '3000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '9'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '4000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '7'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '19'
        },
        {
          store_id: '2001',
          stock: '8'
        },
        {
          store_id: '4000',
          stock: '2'
        }
      ]
    }
  ]
}

使用 JS 我试图解析值并通过商店 ID 对每个值进行排序

例如

使用上面的数据是我想要实现的目标

array['2000'] = ['10 - (3)', '9 - (3)', '7 - (8)']

2000 是 store_id 数组值为size - (stock)

【问题讨论】:

  • 不,array['2000'] 应该只是 ["10 - (3)", "9 - (3)" ]。 [7-(8)] 属于 array[2001]。检查我的answer below 以获得结果。

标签: javascript arrays json dictionary parsing


【解决方案1】:

简单的方法是使用Array#reduce 来聚合您的数据。

此外,在每个inventory 中,您应该整合所有项目以定义具有正确结构的值,例如${attributes[0].value} - (${stock})

const yourJson = {data:[{attributes:[{type:'size',value:'10'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'10'},{store_id:'2000',stock:'3'},{store_id:'3000',stock:'5'}]},{attributes:[{type:'size',value:'9'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'10'},{store_id:'2000',stock:'3'},{store_id:'4000',stock:'5'}]},{attributes:[{type:'size',value:'7'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'19'},{store_id:'2001',stock:'8'},{store_id:'4000',stock:'2'}]}]};

const result = yourJson.data.reduce((acc, {attributes, inventory}) => 
{
  for(const {store_id, stock} of inventory){
    acc[store_id] = acc[store_id] ||[];
    acc[store_id].push(`${attributes[0].value} - (${stock})`);
  }
  
  return acc;
}, {});

console.log(result);

【讨论】:

  • 感谢您 :) 现在测试一下。之前没有听到太多或研究过数组减少,所以我很感激支持。
  • 刚刚在我的代码中尝试过,在节点 js 中它不会让我做 acc[store_id] ??= []; ^ SyntaxError: Unexpected token '?
  • 您可以更改为acc[store_id] = acc[store_id] ||[];。我刚刚更新了我的答案,请看一下
  • 这样好吗? @卡梅隆-华莱士?
  • 感谢您的帮助 :) 只是想了解代码的作用,以便我了解未来。所以你减少 JSON 以便更容易映射或循环数组中的每个对象?那么我唯一不明白的其他一点是 acc[store_id] = acc[store_id] ||[];只是将其设置为空白数组或包含项目的数组,以便它可以继续添加到该数组?
【解决方案2】:

您想使用reduce() 来选择库存中的项目。

这是一个例子:

let response = {
  data: [
    {
      attributes:[
        {
          type: 'size',
          value: '10'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '3000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '9'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '4000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '7'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '19'
        },
        {
          store_id: '2001',
          stock: '8'
        },
        {
          store_id: '4000',
          stock: '2'
        }
      ]
    }
  ]
}

let selected_inventory = response.data.reduce((a, b) => a = b.inventory.find(inv => inv.store_id === '2000') || a, {})
console.log(selected_inventory) // Expected Result: { "store_id": "2000", "stock": "3" }

【讨论】:

    【解决方案3】:

    另一个答案似乎并没有完全按照您想要的格式给出。

    function toObj(arr) {
      const obj = {};
    
      for (const { attributes, inventory } of arr) {
        // Watch out, this assumes there will always be a "size" attribute
        const size = attributes.find(a => a.type === 'size').value;
    
        for (const inv of inventory) {
          // Assign array if it doesn't exist
          // This will be, for ex, obj['2000']
          obj[inv.store_id] = obj[inv.store_id] || [];
    
          // Constructs and pushes the final strings
          obj[inv.store_id].push(size + ' - (' + inv.stock + ')');
        }
      }
      
      return obj;
    }
    
    const INPUT = {
      data: [{
          attributes: [{
              type: 'size',
              value: '10'
            },
            {
              type: 'colour',
              value: 'red'
            }
          ],
          inventory: [{
              store_id: '1000',
              stock: '10'
            },
            {
              store_id: '2000',
              stock: '3'
            },
            {
              store_id: '3000',
              stock: '5'
            }
          ]
        },
        {
          attributes: [{
              type: 'size',
              value: '9'
            },
            {
              type: 'colour',
              value: 'red'
            }
          ],
          inventory: [{
              store_id: '1000',
              stock: '10'
            },
            {
              store_id: '2000',
              stock: '3'
            },
            {
              store_id: '4000',
              stock: '5'
            }
          ]
        },
        {
          attributes: [{
              type: 'size',
              value: '7'
            },
            {
              type: 'colour',
              value: 'red'
            }
          ],
          inventory: [{
              store_id: '1000',
              stock: '19'
            },
            {
              store_id: '2001',
              stock: '8'
            },
            {
              store_id: '4000',
              stock: '2'
            }
          ]
        }
      ]
    }
    
    console.log(toObj(INPUT.data));

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2018-03-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多