1

How do I convert an array into an object with properties: With the following data: ["Test Scenario ID", "Login-1"]

I would like to return an object with properties:

{1: "Test Scenario ID", 2: "Login-1"} // desired result

With the following, It maps the data into separate objects, but I would like it to be properties of a single object instead of an array of objects:

row.values.map( (e,i) => { return {i: e} })

[{1: "Test Scenario ID"}, {2: "Login-1"}] // the current result
pilchard
  • 12,414
  • 5
  • 11
  • 23
codecustard
  • 311
  • 3
  • 9
  • 1
    How does changing your data to this format help you? It seems entirely redundant. – Andy Aug 24 '21 at 01:05

2 Answers2

2

One option is to use Object.fromEntries to turn an array of entries into the object.

const result = Object.fromEntries(
  row.values.map((e, i) => [i, e])
);

Another option is to take your array of multiple objects and put it through Object.assign to combine them.

const result = Object.assign(
  ...row.values.map( (e,i) => ({i: e}))
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

you can use this:

Object.assign({}, ['a','b','c']);    // {0:"a", 1:"b", 2:"c"}

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

you can read more about it here on MDN

Haitham6373
  • 1,139
  • 8
  • 10