Patricio Vargas
Patricio Vargas

Reputation: 5522

Best way to map and objects in an array to single object

I'm trying to map the answer property based on the type to a new single object

const questionsArray = [
  {
    question: `What is your name?`,
    type: "name"
  },
  {
    question: `What is your age?`,
    type: "age"
  }
]

Which will result to this:

bday = {
          name: 'Jose',
          age: '23',
        }

This won't work because every question will replace the previous value already set since the type will be different

Upvotes: 0

Views: 128

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use reduce() and use type as key and answer as value for that key

const questionsArray = [  {    id: 0,    question: `What is your name?`,    answer: 'jose',    type: "name"  },  {    id: 1,    question: `What is your birth month?`,    answer: 'January',    type: "month"  },  {    id: 2,    question: `What day in were you born?`,    answer: '24',    type: "day"  },  {    id: 3,    question: `What's your email?`,    answer: '[email protected]',    type: 'email'  }]

const res = questionsArray.reduce((ac, {type, answer}) => {
  ac[type] = answer;
  return ac;
}, {});
console.log(res)

As you will notice in the above way you can't use any other keys other than type property of array values.

If you want to have custom property names in resulting object you need to have an hash table.

const questionsArray = [  {    id: 0,    question: `What is your name?`,    answer: 'jose',    type: "name"  },  {    id: 1,    question: `What is your birth month?`,    answer: 'January',    type: "month"  },  {    id: 2,    question: `What day in were you born?`,    answer: '24',    type: "day"  },  {    id: 3,    question: `What's your email?`,    answer: '[email protected]',    type: 'email'  }]

const table = {
  day: 'birthDay',
  month: 'birthMonth'
}

const res = questionsArray.reduce((ac, {type, answer}) => {
  ac[table[type] || type] = answer;
  return ac;
}, {});
console.log(res)

Upvotes: 2

Nick Parsons
Nick Parsons

Reputation: 50674

You can use .map() to map each object to an new object with which has the type as the key and the answer as the value. You can then use Object.assing() to build one larger resulting object from this array of mapped objects:

const questionsArray = [ { id: 0, question: `What is your name?`, answer: 'jose', type: "name" }, { id: 1, question: `What is your birth month?`, answer: 'January', type: "month" }, { id: 2, question: `What day in were you born?`, answer: '24', type: "day" }, { id: 3, question: `What's your email?`, answer: '[email protected]', type: 'email' } ];

const bday = Object.assign(...questionsArray.map(({answer, type}) => ({[type]: answer})));
console.log(bday);

Upvotes: 2

Related Questions