如何在反应中将对象值数组更改为对象值数组对象
How change object value array to object value array object in react
我有一个像这样的对象值数组:
{
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}]
}
您可以使用 Object.entries 遍历对象,这将为您提供一个包含对象的每个 属性 的 [key, value] 的数组,然后创建一个 reduce 函数来构建returns 使用映射函数修改数组的新对象:
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)
我有一个像这样的对象值数组:
{
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}]
}
您可以使用 Object.entries 遍历对象,这将为您提供一个包含对象的每个 属性 的 [key, value] 的数组,然后创建一个 reduce 函数来构建returns 使用映射函数修改数组的新对象:
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)