简体   繁体   English

将数组中的项目添加到另一个数组中的对象中

[英]Adding items from array into objects within another array

I am currently looping through the data that I have, getting all values for a specific column and adding them to an array, then limiting it to only unique values.我目前正在遍历我拥有的数据,获取特定列的所有值并将它们添加到数组中,然后将其限制为唯一值。

I also have a reportSections array that needs to be dynamic based on how many items are currently in my date_group array.我还有一个reportSections数组,它需要根据我的date_group数组中当前有多少项目而动态变化。 How can I loop through those arrays and add the values to the id and name objects within my reportSections array?如何遍历那些 arrays 并将值添加到我的reportSections数组中的idname对象?

Ideally, I'm thinking there might contain some sort of for loop that can loop through the reportSections array and dynamically add the values inside the date_group and record_group arrays to the id and name objects, but not sure how that would work.理想情况下,我认为可能包含某种 for 循环,它可以遍历reportSections数组并动态地将date_grouprecord_group arrays 中的值添加到idname对象,但不确定它是如何工作的。

  var date_group = [];
  var record_date = [];
    var i;
    for (i = 0; i < data.length; i++) {
      date_group.push(data[i]['date group']);
      record_date.push(data[i]['record date']);
    }

    date_group = _.uniq(date_group);
    record_date = _.uniq(record_date);

  const reportSections = [
    {id: 'date_group1', name: 'record_date1'},
    {id: 'date_group2', name: 'record_date2'},
    {id: 'date_group3', name: 'record_date3'},
    {id: 'date_group4', name: 'record_date4'},
    {id: 'date_group5', name: 'record_date5'},
    {id: 'date_group6', name: 'record_date6'},
  ];

Regarding making items unique im confused looking at your question but try this solution.关于使项目独一无二,我在看您的问题时感到困惑,但请尝试此解决方案。

Use set for unique recordsset用于唯一记录

 let data = [{ "date group": "C", "record date": "13 Mar 20" }, { "date group": "B", "record date": "11 Mar 20" }, { "date group": "A", "record date": "11 Mar 20" }, { "date group": "B", "record date": "12 Mar 20" }, { "date group": "C", "record date": "11 Mar 20" } ] let reportSections = []; let dataGroups = new Set(); let recordDates = new Set(); data.forEach(item => { dataGroups.add(item['date group']); recordDates.add(item['record date']) }) for (const [index, value] of [...dataGroups].entries()) reportSections.push({ id: value, name: [...recordDates][index] }) console.log(reportSections);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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

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