【问题标题】:Reorganizing JSON data with associative array in Javascript [duplicate]在Javascript中使用关联数组重新组织JSON数据[重复]
【发布时间】:2021-05-19 22:29:54
【问题描述】:

我有一些类似以下的数据:

let foodsArray = [
   {
        "food" : "fruit",
        "type" : "apple"
   } ,
   {
        "food" : "vegetable",
        "type" : "carrot"
   } ,
   {
        "food" : "vegetable",
        "type" : "lettuce"
   } ,
   {
        "food" : "fruit",
        "type" : "orange"
   } ,
]

我想重组如下:

newFoodsArray = [
    {
        "food" : "fruit",
        "type" : ["apple","orange"]
   } ,
   {
        "food" : "vegetable",
        "type" : ["carrot", "lettuce"]
   } ,
]

什么是迭代这些信息并构建我想要的结果的有效方法?我正在尝试这样的事情,但在语法上它不会飞。

for (let i = 0; i < foodsArray; i++) 
     newFoodsArray[foodsArray[i]["food"]].push(foodsArray[i]["type"]);

【问题讨论】:

    标签: javascript associative-array


    【解决方案1】:

    您可以使用reduce 轻松实现此结果。

    let foodsArray = [
      {
        food: "fruit",
        type: "apple",
      },
      {
        food: "vegetable",
        type: "carrot",
      },
      {
        food: "vegetable",
        type: "lettuce",
      },
      {
        food: "fruit",
        type: "orange",
      },
    ];
    
    const newFoodsArray = foodsArray.reduce((acc, { food, type }) => {
      const isExist = acc.find((el) => el.food === food);
      if (isExist) isExist.type.push(type);
      else acc.push({ food, type: [type] });
      return acc;
    }, []);
    
    console.log(newFoodsArray);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多