简体   繁体   English

将数组中的对象和对象映射到单个对象的最佳方法

[英]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这是行不通的,因为每个问题都会替换之前已经设置的值,因为类型会有所不同

You can use reduce() and use type as key and answer as value for that key您可以使用reduce()并使用type作为键并将answer作为该键的值

 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: 'k@k.gmail.com', 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.正如您将在上述方式中注意到的,除了数组值的type属性之外,您不能使用任何其他键。

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: 'k@k.gmail.com', 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)

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.您可以使用.map()将每个对象映射到一个以type为键、以answer为值的新对象。 You can then use Object.assing() to build one larger resulting object from this array of mapped objects:然后,您可以使用Object.assing()从这个映射对象数组构建一个更大的结果对象:

 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: 'k@k.gmail.com', type: 'email' } ]; const bday = Object.assign(...questionsArray.map(({answer, type}) => ({[type]: answer}))); console.log(bday);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM