skip to Main Content

I have an array of objects, for each element inside the array contains the same field as roleMapping. I want to find all elements with the same key combined into an array. Below is the list of object array that I want to convert

a = [
  {
    roleMapping: {
      123: {
        shortName: "1",
        name: "2"
      },
      234: {
        shortName: "123",
        name: "123"
      },
    } 
  },
  {
    roleMapping: {
      123: {
        shortName: "3",
        name: "4"
      }
    } 
  },
  {
    roleMapping: {
      234: {
        shortName: "3",
        name: "4"
      }
    } 
  }
]

I want to result:

a = {
    123: [
        {
                shortName: "1",
                name: "2"
        },
        {
                shortName: "3",
                name: "4"
        }
    ],
    234 : [
        {
                shortName: "123"
                name: "123"
        },
        {
                shortName: "3",
                name: "4"
        }
    ]
}

The purpose I use this is so that when I want to access the shortName, I rely on the key of the object to find the value to use.

2

Answers


  1. You can try with reduce

    const a = [
      {
        roleMapping: {
          123: {
            shortName: "1",
            name: "2"
          },
          234: {
            shortName: "123",
            name: "123"
          },
        } 
      },
      {
        roleMapping: {
          123: {
            shortName: "3",
            name: "4"
          }
        } 
      },
      {
        roleMapping: {
          234: {
            shortName: "3",
            name: "4"
          }
        } 
      }
    ]
    
    const b = a.reduce((acc,{roleMapping}) => {
      Object.entries(roleMapping).forEach(([k,v]) => (acc[k]??=[]).push(v))
      return acc
    },{})
    
    console.log(b)
    Login or Signup to reply.
  2. The function convert in the following code snippet does the required job:

    function convert (a) {
      let b = {};
      for (let { roleMapping } of a) {
        for (let [k, v] of Object.entries(roleMapping)) {
          (b[k] || (b[k] = [])).push(v);
        }
      }
      return b;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search