简体   繁体   中英

Check object has the key and value

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});
  //}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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