fingers10
fingers10

Reputation: 7947

How to merge string array values to a particular property in object array in Type Script / Java Script

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.

Upvotes: 1

Views: 95

Answers (3)

adiga
adiga

Reputation: 35222

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)

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44107

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 } });

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

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)

Upvotes: 1

Related Questions