如何在Type Script / Java Script中将字符串数组值合并到对象数组中的特定属性

时间:2019-03-03 10:04:59

标签: javascript arrays string typescript object

我有一个问题对象

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的新手。请协助我解决问题。

3 个答案:

答案 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)