根据唯一键/名称过滤状态数据数组,并推送到新数组

时间:2019-06-24 12:07:28

标签: javascript reactjs

希望我能正确解释。我有状态=>名为课程的数组,该数组在渲染时存储来自我的API调用的数据。

现在,如果我遍历所有项目,我都会得到这个(25个结果中有1个):

{
  course_department: 'Department A',
  course_pathway: 'BOL',
  course_werkgever: 'DeltaL',
}

现在,我想要的是,因为更多的项具有相同的值course_werkgever,我想针对每种不同的course_werkgever类型提取一次,并将其推入新数组。

因此,我可以像这样在html中使用它:

<select>
  <option value="">Sorteer by Course</option>
  <option value="DeltaL">DeltaL</option>
  <option value="DRZ">DRZ</option>
  <option value="FIA">FIA</option>
</select>

这怎么办?

2 个答案:

答案 0 :(得分:1)

您可以简单地在course_werkgever上创建带有唯一键的对象,以仅获取该对象一次,然后获取该对象的所有值以获取结果数组。这与set的工作原理十分相似:

var arr = [{
  course_department: "Department A",
  course_pathway: "BOL",
  course_werkgever: "DeltaL"
},
{
  course_department: "Department C",
  course_pathway: "FIA",
  course_werkgever: "FIA"
},
{
  course_department: "Department B",
  course_pathway: "DRZ",
  course_werkgever: "DRZ"
},
{
  course_department: "Department B",
  course_pathway: "DRZ",
  course_werkgever: "DRZ"
},
{
  course_department: "Department C",
  course_pathway: "FIA",
  course_werkgever: "FIA"
},
{
  course_department: "Department A",
  course_pathway: "BOL",
  course_werkgever: "DeltaL"
}
];

var tempObj = {};
arr.forEach((obj) => {
  if(!tempObj[obj.course_werkgever]) {
    tempObj[obj.course_werkgever] = obj.course_werkgever;
  }
});
// get the unique array
var res = Object.values(tempObj);
// create HTML select
res.forEach((course_werkgever) => {
  $('#select').append('<option value="'+course_werkgever+'">'+course_werkgever+'</option>');
});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select">
<option value="">Sorteer by Course</option>
</select>

答案 1 :(得分:0)

您可以执行以下操作

    var arr = [{
    course_department: "Department A", 
    course_pathway: "BOL", 
    course_werkgever: "DeltaL" 
},{
    course_department: "Department A", 
    course_pathway: "BOL", 
    course_werkgever: "DeltaLA" 
}]
var newarr = [];
arr.forEach(function (item, index) {
  newarr.push(item.course_werkgever);
});

此处的newarr将包含您期望的值。