将带有对象的数组更改为包含对象的新数组

时间:2017-11-16 12:40:45

标签: javascript arrays object

嗨,我有这个带对象的数组,

[
    {
         "QuestionID":1350,
         "Answers":[
                {
                     "AnswerId":"1350_1",                    
                     "selected":true
                },
                {
                     "AnswerId":"1350_2",                    
                     "selected":false
                },
                {
                     "AnswerId":"1350_3",                    
                     "selected":false
                }
         ]
    },
    {
         "QuestionID":1349,
         "Answers":[
                {
                     "AnswerId":"1349_1",                    
                     "selected":false
                },
                {
                     "AnswerId":"1349_2",                    
                     "selected":true
                },
                {
                     "AnswerId":"1349_3",                    
                     "selected":false
                }
         ]
    }
]

但应更改为此,其中answerID是选定的答案ID

[
    {
        "QuestionID": 1350, 
        "AnswerId": "1350_1"
    },
    {
        “QuestionID”: 1349, 
        “AnswerId”: "1349_2"
    }
]

2 个答案:

答案 0 :(得分:4)

你可以这样做:

data.map(item => ({
  QuestionID: item.QuestionID,
  AnswerId: item.Answers.find(answer => answer.selected).AnswerId,
}));

答案 1 :(得分:0)

试试这个

arr.map( s => (s.AnswerId = s.Answers.find( p => p.selected ).AnswerId, delete s.Answers, s) )

解释

  • 使用地图进行迭代
  • 为每个问题迭代答案,找到一个selected == true
  • 删除 answers密钥

演示

var input = [{
    "QuestionID": 1350,
    "Answers": [{
        "AnswerId": "1350_1",
        "selected": true
      },
      {
        "AnswerId": "1350_2",
        "selected": false
      },
      {
        "AnswerId": "1350_3",
        "selected": false
      }
    ]
  },
  {
    "QuestionID": 1349,
    "Answers": [{
        "AnswerId": "1349_1",
        "selected": false
      },
      {
        "AnswerId": "1349_2",
        "selected": true
      },
      {
        "AnswerId": "1349_3",
        "selected": false
      }
    ]
  }
];

var output = input.map(s => (s.AnswerId = s.Answers.find(p => p.selected).AnswerId, delete s.Answers, s));

console.log(output);