0

I am looking to group some data and then map (what I believe the best way to do it, could be wrong) into an array I have created the following JSFiddle.

JSFiddle

The JSFiddle shows the desired result plus some of my commented out methods.

My code is below:

var answers = [
  { 'question_id': 1, 'id': 1,  'answer': 'Cat' },
  { 'question_id': 1,   'id': 2,  'answer': 'Dog' },
  { 'question_id': 2, 'id': 3,  'answer': 'Fish' },
  { 'question_id': 2,   'id': 4,  'answer': 'Ant' }
];

var result=_.chain(answers).groupBy("question_id").map(function(v, i) {
  return {
    question_id: i,
 //   id: _.get(_.find(v, 'id'), 'id'),
    answers:[
        {id: 1, answer: 'Cat'},
            {id: 2, answer: 'Dog'},
//  {id: _.map(v, 'id'), answer: _.map(v, 'answer'),}
    ] 
  }
}).value();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, '  ') + '</pre>';

2 Answers 2

1

You were nearly there. To get the answers without the 'question_id' you need to map across them and omit the property. This could be done using a function for the map:

answers: _.map(v, function(answer){
    return _.omit(answer, 'question_id');
}

or using the omit function where some of the parameters are already applied and then using that as the function for map:

var omitQuestion = _.partialRight(_.omit, 'question_id');

answers: _.map(v, omitQuestion)
Sign up to request clarification or add additional context in comments.

Comments

1

We iterate over each object in the array, and push it to a object with the question_id as the key. If one does not exist we create it. Then we convert the resulting object into an array.

var answers = [
  { 'question_id': 1, 'id': 1,  'answer': 'Cat' },
  { 'question_id': 1,   'id': 2,  'answer': 'Dog' },
  { 'question_id': 2, 'id': 3,  'answer': 'Fish' },
  { 'question_id': 2,   'id': 4,  'answer': 'Ant' }
];
var result = {};
for (var i = 0; i < answers.length; i++) {
  var question_id = answers[i].question_id;
  if(!result[question_id]) {
    result[question_id] = {question_id: question_id, answers: []};
  }
  result[question_id].answers.push({id: answers[i].id, answer: answers[i].answer})
}
result = Object.keys(result).map(function (key) { return result[key]; });
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.