Skip to content
Advertisement

Mapping data from two dictionary and make a resultant one with specific format in javascript

I have a two dictionaries:

featurePermissionMap = {'2':2,'3':1,'4':1} where key is the feature id and it’s value represents the permission type. Like '2':2 means for a feature id 2 we have a permission 2(Read and Write) and '3':1 means for a feature id 3 we have a permission 1(Read-Only)

Second Dictionary:

feature_with_sub_feature = 
[
{ name: 'FeatureA', 
  subfeatures: [
   { id: 2, name: 'Feature2' },
   { id: 3, name: 'Feature3' },
},
.......
];

I need a resultant dictionary like below:

read_write_access_feature = {
  'read':{},
  'write':{}
}

I just want to iterate over feature_with_sub_feature and based on subfeature id, I want output like

read_write_access_feature = {
  'read':{'FeatureA':['Feature3',....],......},
  'write':{'FeatureA':['Feature2',.....],....}
}

I am trying to achieve this using the two forEach. I am new to javascript. Any optimized way would be much appreciated.

Any help/suggestions would be much appreciated.

Advertisement

Answer

Added function getFeatureWithPermission which will return features with permission passed in parameter. Added code explanation in comment.

call getFeatureWithPermission will required permission as below.

let read_write_access_feature = {
  'read': getFeatureWithPermission(1),
  'write': getFeatureWithPermission(2)
};

Try it below.

let featurePermissionMap = {'2': 2, '3': 1, '4': 1};

// return features with permission passed in parameter.
function getFeatureWithPermission(permission) {
  // use reduce to update & return object as requiment
  return feature_with_sub_feature.reduce((a, x) => {
    // return object with key as x.name
    // value as array of names from subfeatures which have respective permission
    // first filter subfeatures for respective permission
    // then use map to select only name from subfeatures
    a[x.name] = x.subfeatures
        .filter(y => featurePermissionMap[y.id] === permission)
        .map(y => y.name);
    return a;
  }, {}); // <- pass empty object as input
}


let feature_with_sub_feature =  [{ 
  name: 'FeatureA', 
  subfeatures: [
    { id: 2, name: 'Feature2' },
    { id: 3, name: 'Feature3' },
  ]
}];

let read_write_access_feature = {
  'read': getFeatureWithPermission(1),
  'write': getFeatureWithPermission(2)
};

console.log(read_write_access_feature);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement