1

I have an array:

const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]

And I want to convert it to an object like this:

const obj = { name: 'Jon', weapon: 'sword', hair: 'shaggy' }

I've tried splitting the array by the = to get the key and value and then mapping the new array and sending those values to an empty object but it doesn't get the right key

const split = arr.map( el => el.split('=') )
let obj = {};
split.map( el => {
  const key = el[0];
  const val = el[1];
  obj.key = val;
  }
)

obj returns as {key: 'shaggy'}

2 Answers 2

4

Generally, to convert an array into an object, the most appropriate method to use is .reduce:

const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ];
const obj = arr.reduce((a, str) => {
  const [key, val] = str.split('=');
  a[key] = val;
  return a;
}, {});
console.log(obj);

You should only use .map when you need to create a new array by carrying out an operation on every item in the old array, which is not the case here.

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

Comments

3

You can use Object.fromEntries

const arr = [ 'name=Jon', 'weapon=sword', 'hair=shaggy' ]

const obj = Object.fromEntries(arr.map(v => v.split('=')))

console.log(obj)

Comments

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.