0

Courses object :

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

Categories object:

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

My Expected result:

finalObjCategoriesobject:

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

// {catname: 'Sales',categoryid: '3'} removed because there is no course present with this category in courses object.

I want to get only those categories records for which categories have the course data how can I do it.?

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});
  //}
}
Mr world wide
  • 4,696
  • 7
  • 43
  • 97
  • 3
    It's not really clear what your asking here, and it doesn't help with the object literals you have shown are invalid, they all have duplicate keynames. – Keith Mar 12 '18 at 13:05
  • your question not clear, from my understanding this could help you https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript – Abdelrahman Hussien Mar 12 '18 at 13:13
  • @Keith I have updated question can you please check once. – Mr world wide Mar 12 '18 at 15:36

1 Answers1

1

Your question is really really unclear, but if I understood it you can use .map and .find to get what you want.

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)

Here is the fiddle.

Boky
  • 11,554
  • 28
  • 93
  • 163
  • you understood little well I want the reverse `result`. only those` categories` should come in` result` which categories have data in `courses` object. – Mr world wide Mar 12 '18 at 15:24
  • 1
    Could you update your question with the wanted result? – Boky Mar 12 '18 at 15:28