2021年4月1日星期四

loop through this Object that contain Array as values and combine all values, sort them, reindex and update values

I have to loop through the object values and sort them in such a way that I remove number 1 & 2 (lets call it index) from Self and Spouse. Then reindex Child3 and Child4 to Child1 and Child2.

Though the Object got from API response looks like below it makes more sense to reindex them as I'll be displaying this information on the screen.

Object looks like:   eligibilityMap: {      "CHIP": [          "CHILD3" // should be Child1      ],      "APTC/CSR": [          "SELF1", //should be Self          "SPOUSE2", //should be Spouse          "CHILD4" //should be Child2      ]  }  

My question is how should I loop through this Object and just sort the child and reindex them?

Expected Result:

newMapping: {      "CHIP": ["Child1"],      "APTC/CSR": ["Self, Spouse and Child2"]  }  

CODE:

var sortedMember = Object.keys(eligibilityMap).reduce((acc, key) => { //fetch the array for the given key var array = eligibilityMap[key]; console.log('array', array); var sortedArray = array.sort( function (firstValue, secondValue) { if (firstValue.indexOf("SELF") >= 0) return -1; if (secondValue.indexOf("SELF") >= 0) return 1;

      if (firstValue.indexOf("SPOUSE") >= 0) return -1;        if (secondValue.indexOf("SPOUSE") >= 0) return 1;          return 0;      });        console.log("sortedArray", sortedArray)      acc[key] = sortedArray;      return acc;    }, {})        $scope.memberString = Object.keys(sortedMember).reduce(function (acc, key) {        var array = sortedMember[key]        var formattedString = array.reduce(function (memberAcc, member, index) {        if (member.indexOf("SELF") >= 0) {          return "Applicant"        }          if (member.indexOf("SPOUSE") >= 0) {          var delimiter = index > 0  ? ", " : "";          return memberAcc + delimiter + "Spouse"        }          if(index === 0) return member;          var delimiter = index === array.length - 1 ? " and " : ", ";        return memberAcc + delimiter + member //CHILD1      }, "");        console.log("STRING", key, formattedString)     acc[key] = formattedString;      return acc;    }, {});  

RESULT: (But still not what I wanted)

MEMBERS STRING {CHIP: "CHILD4", APTC/CSR: "Applicant, Spouse, CHILD3 and CHILD5"}

https://stackoverflow.com/questions/66913195/loop-through-this-object-that-contain-array-as-values-and-combine-all-values-so April 02, 2021 at 08:46AM

没有评论:

发表评论