【问题标题】:Creating an object from API data and adding it to an array dynamically从 API 数据创建对象并将其动态添加到数组中
【发布时间】:2020-01-13 18:14:16
【问题描述】:

我有一个从数据库中提取的数据集。它是一维的,我基本上需要使它更有条理。我将其称为“平面”。

我需要显示一个标题,以及该标题下与该标题相关的项目。

数据包含 section_name(标题)和 item_name(项目)以及每个项目独有的其他数据,例如下载 URL 等。

  1. item_name(item)_______section_name(header)
  2. 第一个_________________资金
  3. 第二个________________资金
  4. 第三个_________________基金
  5. 第四名__文学
  6. 第五___文学
  7. 第六___文学
  8. 第七篇_______________文学
  9. 第八名________________DueDilligence

我不知道项目或部分的名称是什么,或者每个部分有多少项目、部分或项目。正如我所说,它非常平坦。这需要完全动态,这就是为什么这对我来说很复杂。

这是我所做的。

  1. API 调用来检索数据。将状态中的数据存储为数组(以对象数组的形式出现)。
  2. 我创建了一个空数组来存储我的新结构化数据。
  3. 我使用 foreach 遍历数据。
  4. 我为我的新数据创建了一个新对象以添加到新数组中,以便以后循环遍历它。
  5. 我首先检查以确保数据存在。
  6. 为了创建标头,我检查我的新空数组是否实际上为空,或者我的 section_name 与上一个不同。(在我从 API 调用获得的原始数据数组中)
  7. 我将 section_names 作为对象存储在新数组中 (newArray.push(newObject)

我已经走到这一步了。现在我需要获取与 section_names 相关的 item_names 并将它们存储在每个标题名称下的对象中,或者至少存储在同一个索引中。

 _generateInfo() { 

        let dataArray = this.state.stepTwoData
        let newArray =[]

        dataArray.forEach(function(item, index) {
            let newObject = {}
            if (index > 0) {
                if (newArray.length === 0 || item.investor_portal_section_name !== dataArray[index -1].investor_portal_section_name) {
                    newObject["name"] = item.investor_portal_section_name
                    newObject["items"] = []
                    newArray.push(newObject)
            } 

        })
        console.log(newArray)
    }

我尝试将项目推送到我的新对象上的“数字”数组中,但这似乎无法正常工作。有时它会重复我的 newObject.name

检查 newObject.name === 数组中的 section_names 是否并将其推送到我的新对象中的“数字”数组只会创建新的键值对,因此它仍然不相关。

我尝试在 if 语句中再次循环,如果 section_name === newObject.name 然后创建一个 newObject 并推送它,但它只会重复推送其中一个项目,而不是遍历所有项目。

我需要循环并创建一个标题(每个不同的 section_name 一个标题)。然后将与 section_name 对应的每个项目添加到它。像这样

[
{section_name(header): "Funds",
items: [
 {
  name: item_name,
  sku: item_sku,
  url: item_url
},
{
 name: item_name,
 sku: item_sku,
 url: item_url
}]
},
{section_name(header):"Literature",
items: [
 {name: item_name,
  sku: item_sku,
  url: item_url
},
{
 name: item_name,
 sku: item_sku,
 url: item_url
}]}
]

【问题讨论】:

    标签: javascript arrays reactjs foreach javascript-objects


    【解决方案1】:

    使用关联数组(字典)按类别分离数据项就可以了。 我已经起草了一些 POC 代码来说明这个想法。关键元素是buildAssociativeArray函数

    const raw_data = [
        {item_name: "first", section_name: "Funds"}, 
        {item_name: "second", section_name: "Funds"}, 
        {item_name: "third", section_name: "Funds"}, 
        {item_name: "fourth", section_name: "Literature"}, 
        {item_name: "fifth", section_name: "Literature"}, 
        {item_name: "sixth", section_name: "Literature"}, 
        {item_name: "seventh", section_name: "Literature"}, 
        {item_name: "eighth", section_name: "DueDilligence"}, 
    ]
    
    function buildAssociativeArray(data) {
        const dictionary = {};
        for (var i = 0; i < data.length; i++) {
            const item = data[i];
            const section = item.section_name;
            var dictEntry = dictionary[section];
            if (!dictEntry) {
                dictEntry = [];
                dictionary[section] = dictEntry;
            }
            dictEntry.push({
                name: item.item_name,
                //    other fields like sku: item_sku or url: item_url may follow here
            });
        }
        return dictionary;
    }
    
    const dictionary = buildAssociativeArray(raw_data);
    console.log(dictionary);
    /*
    At this point
    dictionary == {
      "Funds": [
        {
          "name": "first"
        },
        {
          "name": "second"
        },
        {
          "name": "third"
        }
      ],
      "Literature": [
        {
          "name": "fourth"
        },
        {
          "name": "fifth"
        },
        {
          "name": "sixth"
        },
        {
          "name": "seventh"
        }
      ],
      "DueDilligence": [
        {
          "name": "eighth"
        }
      ]
    }
    */
    
    //    Associcative array dictionary itself allows to further solve you task using for (var key in dictionary) {...} operator
    //    If however you need to obtain the data structure looking exactly like the one in your question you may go further with following function
    
    function transformAssociativeArray(dictionary) {
        const array = [];
        for (var key in dictionary) {
            const items = dictionary[key];
            const newEntry = {
                section_name: key,
                items: items,
            }
            array.push(newEntry);
        }
        return array;
    }
    
    const array = transformAssociativeArray(dictionary);
    console.log(array);
    /*
    
    At this point
    array == [
      {
        "section_name": "Funds",
        "items": [
          {
            "name": "first"
          },
          {
            "name": "second"
          },
          {
            "name": "third"
          }
        ]
      },
      {
        "section_name": "Literature",
        "items": [
          {
            "name": "fourth"
          },
          {
            "name": "fifth"
          },
          {
            "name": "sixth"
          },
          {
            "name": "seventh"
          }
        ]
      },
      {
        "section_name": "DueDilligence",
        "items": [
          {
            "name": "eighth"
          }
        ]
      }
    ]
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 2022-07-28
      • 1970-01-01
      • 2013-02-27
      • 2012-09-26
      相关资源
      最近更新 更多