reactjs (已关闭)如何将对象值数组更改为对象值数组对象

iswrvxsc  于 2022-12-29  发布在  React
关注(0)|答案(1)|浏览(186)

我有一个对象值数组,如下所示:

{
    user: ["data1", "data2"],
    user2: ["data1", "data2"],
}

我想将对象值数组更改为对象值数组对象,如下所示:

{
    user: [{value: "data1", name: "data1", isChecked: false}, {value: "data2",  name: "data2", isChecked: false}],
    user2: [{value: "data1", name: "data1", isChecked: false}, {value: "data2",  name: "data2", isChecked: false}]
}
3duebb1j

3duebb1j1#

你可以使用Object.entries迭代对象,它会给予你一个数组,其中包含对象的每个属性的[key,value],然后创建一个reduce函数来构建一个新的对象,该对象使用map函数返回修改后的数组:

const obj = {
    user: ["data1", "data2"],
    user2: ["data1", "data2"],
}
const result = Object.entries(obj).reduce((acc, curr) => {
 const [key, value] = curr

 return {
  ...acc,
  [key]: value.map(item => ({ value: item, name: item, isChecked: false}))
 }

}, {})

console.log(result)

相关问题