arraysreactjsobjectnext.jsarrayobject

(closed) How change object value array to object value array object in react


i have a object value array like this:

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

and i want change a object value array to object value array object like this:

{
    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}]
}

Solution

  • You can iterate over the object using Object.entries that will give you an array with the [key, value] of each property of the object and after that just create a reduce function to build a new object that returns the modified array using a map function:

    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)