简体   繁体   English

根据API数据创建对象并将其动态添加到数组中

[英]Creating an object from API data and adding it to an array dynamically

I have a data set that I'm pulling in from a database. 我有一个要从数据库中提取的数据集。 It's one dimensional and I basically need to make it more structured. 这是一维的,我基本上需要使其更有条理。 I refer to it as "flat". 我称其为“扁平”。

I need to display a heading, and items under that heading that are related to the heading. 我需要显示一个标题,以及该标题下与该标题相关的项目。

The data comes in as having and section_name (the heading) and item_name (items) and other data unique to each item like download URLs etc. 数据以具有and section_name(标题)和item_name(项目)以及每个项目唯一的其他数据(例如下载URL等)的形式出现。

  1. item_name(item)_______section_name(header) item_name(项目)_______ section_name(标题)
  2. first_________________Funds first_________________资金
  3. second________________Funds 第二笔资金
  4. third_________________Funds third_________________资金
  5. fourth________________Literature 第四篇
  6. fifth_________________Literature 第五_________________文学
  7. sixth_________________Literature 第六_________________文学
  8. seventh_______________Literature 第七_______________文学
  9. eighth________________DueDilligence 第八名:尽职调查

I don't know what any of the names will be for the items or sections, or how many items, sections, or items per section. 我不知道这些项目或部分的名称是什么,或者每个部分有多少个项目,部分或项目。 As I said, it's very flat. 如我所说,它非常平坦。 This needs to be fully dynamic which is why this is complicating things for me. 这需要是完全动态的,这就是为什么这会使我复杂化。

Here is what I've done. 这是我所做的。

  1. API call to retrieve data. API调用以检索数据。 Store data in a state as an array (it comes in as an array of objects). 将状态存储为数组的数据(作为对象数组存储)。
  2. I create an empty array to store my newly structured data. 我创建一个空数组来存储我的新结构化数据。
  3. I loop through the data with a foreach. 我用foreach遍历数据。
  4. I create a new object for my new data to add to the new array so I can loop over it later. 我为新数据创建了一个新对象,以将其添加到新数组中,以便以后可以对其进行循环。
  5. I first check to make sure the data exists. 我首先检查以确保数据存在。
  6. To create the headers I check to see if my new empty array is actually empty OR my section_name is not the same as the last one.(in the original data array I got from the API call) 为了创建头文件,我检查我的新空数组是否实际上是空的,或者我的section_name与上一个不同(在我从API调用获得的原始数据数组中)
  7. I store the section_names as an object in the new array (newArray.push(newObject) 我将section_names作为对象存储在新数组(newArray.push(newObject)

I've gotten this far. 我已经走了这么远。 Now I need to take the item_names that correlates to the section_names and store them in the object under each header name, or at least in the same index. 现在,我需要获取与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)
    }

I tried pushing the items to the "number" array on my new object and that doesn't seem to work properly. 我尝试将项目推送到新对象上的“数字”数组中,但这似乎无法正常工作。 Sometimes it will duplicate my newObject.name 有时它将复制我的newObject.name

Checking if the newObject.name === the section_names in the array and push it to the "number" array in my new object just creates new key-value pairs so it's still not correlating. 检查newObject.name ===数组中的section_names并将其推入新对象中的“ number”数组中只会创建新的键-值对,因此它仍然没有关联。

I tried looping through again in the if statement and if section_name === newObject.name then create a newObject and push it, but it would only push one of the items repeatedly instead of going through all of them. 我尝试在if语句和if section_name === newObject.name中再次循环遍历,然后创建一个newObject并推送它,但是它只会重复推送其中一项,而不是遍历所有项。

I need to loop through and create a header (one header per different section_name). 我需要遍历并创建一个标题(每个不同的section_name一个标题)。 Then add each item that corresponds to the section_name to it. 然后将与section_name对应的每个项目添加到其中。 like this 像这样

[
{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
}]}
]

Using associative array (dictionary) to segregate you data itmes by categories will do the job. 使用关联数组(字典)按类别将您的数据主题分类将可以完成工作。 I've drafted some POC code that illustrates the idea. 我起草了一些POC代码来说明这个想法。 The key element there is buildAssociativeArray function 关键元素是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"
      }
    ]
  }
]
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM