需要功能帮助处理此数据结构

时间:2017-04-11 15:08:45

标签: javascript lodash

我有这个数据结构:

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的解决方案。

2 个答案:

答案 0 :(得分: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)

请注意,这不会存储诸如“你的名字是什么?”之类的内容:“”但这是不必要的,如果用户已经回答了这个问题,你可以查看hasOwnProperty

答案 1 :(得分: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);