簡體   English   中英

將數組中的對象和對象映射到單個對象的最佳方法

[英]Best way to map and objects in an array to single object

我正在嘗試將基於類型的答案屬性映射到一個新的單個對象

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

這將導致:

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

這是行不通的,因為每個問題都會替換之前已經設置的值,因為類型會有所不同

您可以使用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)

正如您將在上述方式中注意到的,除了數組值的type屬性之外,您不能使用任何其他鍵。

如果要在結果對象中包含自定義屬性名稱,則需要有一個哈希表。

 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)

您可以使用.map()將每個對象映射到一個以type為鍵、以answer為值的新對象。 然后,您可以使用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