0

enter image description hereI have the following array and a picture of how the structure of it returns to me:

const connections = [1:{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"},
                     1:{fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}
                    ]

and I need to create an object with this structure to be compatible with my code:

"connections": {
    "0": {
      "fromBox": "0",
      "fromConnector": "port_0",
      "toBox": "1",
      "toConnector": "port_0",
    },
    "1": {
      "fromBox": "0",
      "fromConnector": "port_1",
      "toBox": "1",
      "toConnector": "port_1"
    }
  }

Looking at similar doubts I have understood that with a reduction method I should be able to achieve it but when trying to put the index, that they have in the array, into the object it gives me as if the elements of the array were undefined

      const connectionsKeys = Object.keys(connections);

      const result = connections.reduce((c, v) => {
        c[v.connectionsKeys] = c[v.connectionsKeys] || {}; 

        return c;
      }, {});

Any help or guidance would be appreciated. Thank you in advance

2
  • 3
    connections is not a valid array. Commented Apr 15, 2020 at 15:20
  • @palaѕн the array is returned to me by the database Commented Apr 15, 2020 at 15:41

2 Answers 2

1

const connections = [{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"},
                     {fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}
                    ]


function convertToObject(arr){
  return Object.assign({},arr)
}

console.log(convertToObject(connections));

Sign up to request clarification or add additional context in comments.

Comments

1

The first picture from your post (the one from the console) differs structurally from the one assigned to the constant connections. The picture translated into js code should look like this

const connections = [{1:{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"}},
                 {1:{fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}}
                ]

From this structure, you can do the following reduction to end up with the structure you need:

const result = connections.reduce((acc, curr, index) => {
    acc[index] = curr['1'];

    return acc;
  }, {});

1 Comment

thank, the original structure was a mistake from a previous function that I've corrected, but I take note from your solution 'cause I didn´t know how to correct it!! @answered many thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.