Check对象具有键和值

时间:2018-03-12 12:57:32

标签: javascript arrays json object filter

课程对象:

data.courses: [{name: 'JAVA', categoryid: '1'},
{name: 'PHP', categoryid: '1'},
{name: 'HR', categoryid: '2'}]

类别对象:

data.categories: [{catname: 'Information technology',categoryid: '1'},
{catname: 'HR',categoryid: '2'},
{catname: 'Sales',categoryid: '3'}]

我的预期结果:

finalObjCategoriesobject:

 data.finalObjCategories: [{catname: 'Information technology',categoryid: '1'},
 {catname: 'HR',categoryid: '2'}] 

// {catname: 'Sales',categoryid: '3'}已删除,因为课程对象中没有此类别的课程。

我想只获取那些类别包含课程数据的类别记录,我该怎么办呢?

while(grCategory.next())  {
  var categoryName=grCategory.getValue('name');
  var categoryId=grCategory.getUniqueValue();
  //here condition needed(couse cat lenght > 1 push else dontpush)
  //if (data.courses.hasOwnProperty('name');){
      data.categories.push({name: categoryName, id: categoryId});
  //}
}

1 个答案:

答案 0 :(得分:1)

您的问题确实非常不清楚,但如果我理解了您可以使用.map.find来获得您想要的内容。



var courses =  [
  {name: 'JAVA',categoryid: '1'},
  {name: 'PHP',categoryid: '1'},
  {name: 'HR',categoryid: '2'}
]
                
var categories = [
  {catname: 'Information technology',categoryid: '1'},
  {catname: 'HR',categoryid: '2'},
  {catname: 'Sales',categoryid: '3'}
]

var result = [];
courses.map(function(course){
  var crs = categories.find(function(cat){return course.categoryid == cat.categoryid})

  if(typeof crs !== "undefined" && result.indexOf(crs) < 0){
    result.push(crs);
  }    
})

console.log(result)
&#13;
&#13;
&#13;

Here is the fiddle.