Home > Enterprise >  Javascript: How to convert array ["a=1", "b=2"] into an object?
Javascript: How to convert array ["a=1", "b=2"] into an object?

Time:04-28

What is the best way to convert:

user = ['Name:Marry', 'Age:24', 'Gender:Female']

to

user = { 'Name':'Marry', 'Age':'24', 'Gender':'Female' }

CodePudding user response:

Here you want to convert an array to a single value( here it is an object ), for this more declarative way is to use reduce method. Here I have given an empty object as the initial value of the accumulator and on each iteration it adds the key value pair.

const result = user.reduce((acc, curr) => {
  const [key, value] = curr.split(':');
  acc[key] = value;
  
  return acc;
}, {});

Hope this helps.

CodePudding user response:

One line solution:

const result = Object.assign({}, ...user.map(item => item.split(':')).map(item => ({ [item[0]]: item[1]})))

CodePudding user response:

    user = ['Name:Marry', 'Age:24', 'Gender:Female']
    const userObj = {}

    for(item of user) {
      const [key, value] = item.split(":")
      userObj[key] = value
    }
    
    console.log(userObj)

  • Related