0

below is my function

getUpdatedGridData(array) {
    return Object.values(array.reduce((acc, { attributeId, ...rest }) => {
        acc[attributeId] = acc[attributeId] || {};
        acc[attributeId].attributeId = attributeId;
        Object.entries(rest).forEach(([key, value]) => {
            if (acc[attributeId][key] && value !== '') {
                acc[attributeId][key] = value;
            }
            if (!acc[attributeId][key]) {
                acc[attributeId][key] = value;
            }
        });
        return acc;
    }, {}));
}

Example array parameter which is sent to the above method


Array(2)
--------
0: {attributeId: 2, objectType: "OPERATORS", attributeName: "PYUSERNAME"}
1: {attributeId: 1, objectType: "PORTFOLIO", attributeName: "PORTFOLIONAME"}

As we can see in 0th position we have attributeId 2 and at 1st index we have attributeId 1. So, when I receive the updated data from above method, the position of the indexes are getting changed. For the above request, at 0th position I am getting attrId 1 and at 1st position I am getting attrId 2. I am not really able to understand how to modify the above method to keep the indexes properly. Please advice. Thanks

aleksxor
  • 7,535
  • 1
  • 22
  • 27
vamsi
  • 1,488
  • 3
  • 28
  • 66
  • what do you think about order the array before iterate/process? This stackoverflow post contains a solution for this: https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value – Antonio Leonardo Jun 07 '21 at 15:12
  • It is not about sorting in asc or desc order. I just want to keep the order as is. It may not have attribute ids in sequence. – vamsi Jun 07 '21 at 15:16
  • Numeric keys of an object are ordered by numeric value of the key. There's no way to change this. – Barmar Jun 07 '21 at 15:17
  • https://stackblitz.com/edit/js-upnub6?file=index.js Though the iteration order is not guaranteed you still can store the initial order and then sort by it later. – aleksxor Jun 07 '21 at 15:24

0 Answers0