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
1
  • 1
    How does changing your data to this format help you? It seems entirely redundant. Commented Aug 24, 2021 at 1:05

2 Answers 2

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}))
);
Sign up to request clarification or add additional context in comments.

2 Comments

How would I use fromEntries if there is an undefined/null entry? e.g.: null, 4, "View nearby bucket lists"
Would you want to remove such values from the resulting object?
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.