0

Good Day,

I'm trying to convert an Array of objects into a single object that is structured like this:

parent:{
 uniqueChildKeyA:{...},
 uniqueChildKeyB:{...},
 .
 .
 .
 uniqueChildKeyZ:{...}
}

I have referred to this SO question

How do I convert array of Objects into one Object in JavaScript?

but couldn't apply it to my scenario since the keys are different from each object property varies from object to object. I am stuck in the part where the array of objects is converted to a single object.

let variables = this.state.propVariableArray

let cssObj = variables.map(variable => {
    let x = "" + variable.x + ""
    let y = "" + variable.y + ""
    let cssProperties = {
        "visibility": "visible",
        "left": x,
        "top": y,
        "width": "auto",
        "color": variable.color,
        "font-size": "" + variable.fontSize,
        "font-family": variable.fontFamily
    }
    let variableStyle = {}
    variableStyle = { [variable.id]: cssProperties }
    return (
        variableStyle
    )
})

let obj = { ...cssObj }
console.log(obj)

The resulting object looks like this:

Array to Single Object

How do I do it such that in the new object that will follow the pattern above, the keys would be the name itself and not the indices from the array?

NoobNewb
  • 583
  • 2
  • 10
  • 21

1 Answers1

2

You could use .reduce instead:

let cssObj = variables.reduce((acc, variable) => {
    let x = "" + variable.x + ""
    let y = "" + variable.y + ""
    let cssProperties = {
        "visibility": "visible",
        "left": x,
        "top": y,
        "width": "auto",
        "color": variable.color,
        "font-size": "" + variable.fontSize,
        "font-family": variable.fontFamily
    }
    acc[variable.id] = cssProperties;
    return acc;
}, {})

Rather than converting your array into another array, it will combine the elements of your array into a single value... in this case, a single object.

JDB
  • 25,172
  • 5
  • 72
  • 123