1

I have a question object

let question = {
    id: 1,
    description: 'how is the service',
    answers: [
      {
         id: 1,
         description: 'poor'
      },
      {
         id: 2,
         description: 'good'
      }
    ]
};

let newquestion = {
    description: 'new question',
    answers: [
        'new poor',
        'new good'
    ]
}

I need to map the answer values to the corresponding description property in the answers array inside the question object.

I need the output to look like,

  q = {
    id: 1,
    description: 'new question',
    answers: [
      {
         id: 1,
         description: 'new poor'
      },
      {
         id: 2,
         description: 'new good'
      }
    ]
};

i tried,

const q = {...question, ...newquestion};

But I get output like,

q = {
    id: 1,
    description: 'new question',
    answers: [
      'new poor',
      'new good'
    ]
};

I'm new to typescript and javascript. Please assist on where I'm going wrong.

3 Answers 3

1

If you're okay with mutating the original question, then just loop through the newquestion.asnwers and update the question.answers using their respective index

let question = {id:1,description:'how is the service',answers:[{id:1,description:'poor'},{id:2,description:'good'}]},
    newquestion={description:'new question',answers:['new poor','new good']};

newquestion.answers.forEach((description, i) => {
  question.answers[i].description = description
})

console.log(question)

If you want to create a new q object, then use map to get the new answers array and create a new object using the spread syntax:

let question = {id:1,description:'how is the service',answers:[{id:1,description:'poor'},{id:2,description:'good'}]},
    newquestion={description:'new question',answers:['new poor','new good']};

const newAnswers = newquestion.answers.map((description, i) => (
    { ...question.answers[i], description }
))

const q = { ...question, answers: newAnswers }
console.log(q)

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

Comments

1

You first need to change answers array in newquestion in desired format.

let question = {id: 1,description: 'how is the service',answers: [{id: 1,description: 'poor'},{id: 2,description: 'good'}]};
let newquestion = {description: 'new question',answers: ['new poor','new good']}

newquestion.answers = newquestion.answers.map((val, index) => ({ id:index+1, description: val }))

let op = {...question, ...newquestion}

console.log(op)

Comments

1

Use a simple map to change the values:

const q = {...question, ...newQuestion};
q.answers = q.answers.map((e, i) => { return { id: i + 1, description: e } });

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.