我有一个问题对象
ClassNotFound
我需要将答案值映射到问题对象内答案数组中的相应描述属性。
我需要输出看起来像
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'
]
}
我尝试过
q = {
id: 1,
description: 'new question',
answers: [
{
id: 1,
description: 'new poor'
},
{
id: 2,
description: 'new good'
}
]
};
但是我得到类似的输出,
const q = {...question, ...newquestion};
我是打字稿和JavaScript的新手。请协助我解决问题。
答案 0 :(得分:1)
您首先需要以所需的格式更改answers
中的newquestion
数组。
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)
答案 1 :(得分:1)
使用简单的map
更改值:
const q = {...question, ...newQuestion};
q.answers = q.answers.map((e, i) => { return { id: i + 1, description: e } });
答案 2 :(得分:1)
如果您可以对原始question
进行突变,那么只需遍历newquestion.asnwers
并使用各自的question.answers
更新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)
如果要创建一个新的q
对象,请使用map
获取新的答案数组并使用传播语法创建一个新的对象:
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)