2017-04-11 90 views
1

我有这样的数据结构:需要的功能帮助处理这种数据结构

let questions=[{ 
    question: "What is your name?", 
    responses: [{ 
     userId: 1, 
     answer: "Geof" 
    }, { 
     userId: 5, 
     answer: "Pete" 
    }] 
}, { 
    question: "Where are you from?", 
    responses: [{ 
     userId: 3, 
     answer: "Earth" 
    }, { 
     userId: 5, 
     answer: "Mars" 
    }] 
},.......] 

我想传播这个对象:

[{ userId: 1, "What is your name?": "geoff", "Where are you from?":"", "another question":....}, 
{ userId: 2, "What is your name?": "", "Where are you from?":"".......} 

因为我无法预测,我得到了什么问题,我我正在寻找一种以这种方式传播它的动态功能。 lodash的解决方案非常受欢迎。

回答

1

let questions=[{ 
 
    question: "What is your name?", 
 
    responses: [{ 
 
     userId: 1, 
 
     answer: "Geof" 
 
    }, { 
 
     userId: 5, 
 
     answer: "Pete" 
 
    }] 
 
}, { 
 
    question: "Where are you from?", 
 
    responses: [{ 
 
     userId: 3, 
 
     answer: "Earth" 
 
    }, { 
 
     userId: 5, 
 
     answer: "Mars" 
 
    }] 
 
}] 
 

 
var responses = {} 
 
questions.forEach(q => q.responses.forEach(res => (responses[res.userId] = responses[res.userId] || {})[q.question] = res.answer)) 
 
console.log(responses) 
 

 
//If you really want it as array : 
 

 
var arr = []; 
 
for (var userId in responses) { 
 
    responses[userId].userId = userId; 
 
    arr.push(responses[userId]); 
 
} 
 

 
console.log(arr)

注意,这不会致使店里的东西,如“你叫什么名字?”:“”但这是unnecesary,你可以用hasOwnProperty检查,如果用户已经回答了这个问题或不

1

什么:

function formatAnswers(qs) { 
    // Format into a map 
    let users = {}; 
    qs.forEach((q) => { 
     q.responses.forEach((r) => { 
      if (users[r.userId] === undefined) { 
       users[r.userId] = { 
        userId: r.userId, 
        [q.question]: r.answer 
       }; 
      } else { 
       users[r.userId][q.question] = r.answer; 
      } 
     }); 
    }); 
    // Transform map into an array 
    let out = []; 
    for (var entry in users) { 
     out.push(users[entry]); 
    } 
    return out; 
} 

let result = formatAnswers(questions); 
console.log(result);