0

here is my use case: I have two arrays of objects that come from two observables and I have created a combineLatest method to iterate the array into one with mapped Ids:

var result1 = [{ question: 1, answerList: [{ answer: 'Sandra', isDefault: 'true' }, { answer: 'John', isDefault: 'false' } ] }, { question: 2, answerList: [{ answer: 'Peter', isDefault: 'false' }, { answer: 'Bobby', isDefault: 'false' } ] }, { question: 3, answerList: [{ answer: 'Harry', isDefault: 'false' }, { answer: 'Bob', isDefault: 'false' } ] } ] var result2 = [{ question: 1, answer: 'John' }, { question: 3, answer: 'Bob' } ]; 

My goal is to have another array of objects containing elements like this:

var finalResult = [{ question: 1, answerList: [{ answer: 'Sandra', isDefault: 'false' }, { answer: 'John', isDefault: 'true' } ] }, { question: 2, answerList: [{ answer: 'Peter', isDefault: 'false' }, { answer: 'Bobby', isDefault: 'false' } ] }, { question: 3, answerList: [{ answer: 'Harry', isDefault: 'false' }, { answer: 'Bob', isDefault: 'true' } ] } ] 
4
  • What have you tried so far? Commented Sep 1, 2018 at 9:17
  • why 'true'/'false' as strings? should a not given question update the questions or leave it? Commented Sep 1, 2018 at 9:21
  • @NinaScholz this is the format it comes in from api Commented Sep 1, 2018 at 9:32
  • and in which format do you need the values? Commented Sep 1, 2018 at 9:37

2 Answers 2

1

You could use a hash table for faster check of an question with an answer is set. Then iterate and update the items according of the object's settings.

var result1 = [{ question: 1, answerList: [{ answer: 'Sandra', isDefault: 'true' }, { answer: 'John', isDefault: 'false' }] }, { question: 2, answerList: [{ answer: 'Peter', isDefault: 'false' }, { answer: 'Bobby', isDefault: 'false' }] }, { question: 3, answerList: [{ answer: 'Harry', isDefault: 'false' }, { answer: 'Bob', isDefault: 'false' }] }], result2 = [{ question: 1, answer: 'John' }, { question: 3, answer: 'Bob' }], object = result2.reduce((o, { question, answer }) => { (o[question] = o[question] || {})[answer] = true; return o; }, Object.create(null)); result1.forEach(({ question, answerList }) => answerList.forEach(o => o.isDefault = (question in object && o.answer in object[question]).toString() ) ); console.log(result1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

Example code:

let result = result1.map(item => { let targetItems = result2.filter( item2 => item2.question === item.question ); targetItems.forEach(item3 => { item.answerList.push(item3.answer); }); return item; }); console.log(result); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.