javascript 是否将数组对象转换为具有相同键的对象?

pvcm50d1  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(193)

我有一个对象数组,数组中的每个元素都包含与roleMapping相同的字段。我想找到所有具有相同键的元素组合成一个数组。下面是我要转换的对象数组列表

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

我想要的结果:

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

我使用它的目的是,当我想访问shortName时,我依靠对象的键来找到要使用的值。

x8diyxa7

x8diyxa71#

你可以试试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)
js4nwp54

js4nwp542#

下面的代码片段中的函数convert完成了所需的工作:

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;
}

相关问题