i have create custom object using 2 arrays contains objects 2 3 properties. based on number of matched items have create object. here don't want use many variables. without using intermediate variables want write code
code
var fn = function() { var list1 = [{aid: 0, name: 'item1'}, {aid: 1, name: 'item2'}, {aid: 2, name: 'item3'}], list2 = [ { id: 0, label: 'one', actions: [ 0, 1, 2 ] }, { id: 1, label: 'two', actions: [ 0, 2 ] } ], customobj ={}; for(var i=0; i<list1.length; i++) { for(var j=0; j<list2.length; j++){ customobj[list2[j].id] = {}; for(var k=0; k<list2[j].actions.length; k++){ if(list1[i].aid == list2[j].actions[k]){ customobj[list2[j].id][list1[i].name] = true } } } } return customobj; } required output:
customobj = { 0: { item1: true, item2: true, item3: true }, 1: { item1:true, item3:true } } can suggest me doing mistake?
you're assigning value entire object instead of 1 property. inside condition, need customobj[list2[j].id][list1[i].name] = true. using brackets access properties (as opposed dots, in customobj.0.item1) here lets assign properties variable names. so, final code like:
var fn = function() { var list1 = [{aid: 0, name: 'item1'}, {aid: 1, name: 'item2'}, {aid: 2, name: 'item3'}], list2 = [ { id: 0, label: 'one', actions: [ 0, 1, 2 ] }, { id: 1, label: 'two', actions: [ 0, 2 ] } ], customobj ={}; for(var i=0; i<list1.length; i++) { for(var j=0; j<list2.length; j++){ for(var k=0; k<list2.actions.length; k++){ if(list1[i].aid == list2[j].actions[k]){ customobj[list2[j].id][list1[i].name] = true; } } } } return customobj; }
Comments
Post a Comment