在数组内的对象内映射对象

时间:2018-12-14 19:24:52

标签: javascript arrays object

我有一个数组,里面有一个对象,其中包含更多我想映射到更简单结构的对象。

我尝试了以下方法,它似乎遍历对象并为每个没有数据的循环返回一个对象。

Object.values(data).forEach((a) => {
  console.log({
    managingRole: a.id === 110 ? a.answer : null,
    advice: a.id === 112 ? a.answer : null,
  });
});

最终目标是返回要映射的对象数组:

const desired = [{
  managingRole: 'spending',
  advice: 'everyone'
},
{
  managingRole: 'saving',
  advice: 'no one'
}];

我正在使用的数据如下:

const data = [{
  '110':
  {
    id: 110,
    type: 'RADIO',
    question: '<strong>My main role in managing my money is:</strong>',
    section_id: 9,
    answer: 'spending'
  },
  '111':
  {
    id: 111,
    type: 'RADIO',
    question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
    section_id: 9,
    answer: 'spend it'
  },
  '112':
  {
    id: 112,
    type: 'RADIO',
    question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
    section_id: 9,
    answer: 'everyone'
  }
 },
 {
  '110':
  {
    id: 110,
    type: 'RADIO',
    question: '<strong>My main role in managing my money is:</strong>',
    section_id: 9,
    answer: 'saving'
  },
  '111':
  {
    id: 111,
    type: 'RADIO',
    question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
    section_id: 9,
    answer: 'save it'
   },
  '112':
  {
    id: 112,
    type: 'RADIO',
    question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
    section_id: 9,
    answer: 'no one'
  }
}];

1 个答案:

答案 0 :(得分:1)

您可以直接使用给定的id寻址对象,这与具有想要的answer的对象的键相同。

const
    data = [{ 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'spending' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'spend it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'everyone' } }, { 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'saving' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'save it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'no one' } }],
    result = data.map(o => ({
        managingRole: o['110'].answer || null,
        advice: o['112'].answer || null
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }