如何在数组中返回带有数组的对象

时间:2019-03-27 18:23:08

标签: reactjs

需要作为对象返回,或者需要从以下数据模型中提取数据的更好方法。

  const dataModel = {
       data:[
        {
         id: '1234',
         entity : [{
           id: '1',
           type: 'books'
         }]
      },
      {
        id: '1234',
        entity : [{
          id: '1',
          type: 'books'
        }]
       }
     ]
  };

我尝试了以下代码

const getBooksId = response.data.map(values => {
  return values.entity.find(entity => 
    entity.type === 'books'
  );
  }).filter( data => data !== undefined);
}
const getMagazineId = response.data.map(values => {
  return values.entity.find(entity => 
    entity.type === 'magazine'
 );
  }).filter( data => data !== undefined);
}
let getDataIntoObject = { bookId: getBooksId[0].id, magazineId: getMagazine[0].id }

getDataIntoObject给了我期望的结果,它是每个实体的id,但是代码看起来很混乱。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

这是一个看起来更好的版本:

const responseData = [
  {
    id: '123',
    entity: [{
      id: '1',
      type: 'books'
    }]
  },
  {
    id: '456',
    entity: [{
      id: '2',
      type: 'books'
    }]
  },
  {
    id: '789',
    entity: [{
      id: '3',
      type: 'magazine'
    }]
  }
];

const entities = responseData.map(d => d.entity).flat();
const book = entities.find(e => e.type === 'books');
const magazine = entities.find(e => e.type === 'magazine');

const getDataIntoObject = {
  bookId: book && book.id,
  magazineId: magazine && magazine.id
};

console.log(getDataIntoObject);

...并处理找不到的bookmagazine