如何将我的数据转换为React Native的SectionList的正确格式?

时间:2017-05-30 17:49:27

标签: javascript arrays react-native javascript-objects

我有一个allPosts数组,看起来像这样。

const allPosts = [
    {
      date: '2017-06-06',
      imageUrl: 'image1_06-06',
    },
    {
      date: '2017-06-06',
      imageUrl: 'image2_06-06',
    },
    {
      date: '2017-06-07',
      imageUrl: 'image1_06-07',
    },
    {
      date: '2017-06-07',
      imageUrl: 'image2_06-07',
    }
];

React Native' s SectionList需要像这样组织。

const postsByDate = [
    {
      data: [{ imageUrl: 'image1_06-06' }, { imageUrl: 'image2_06-06' }],
      key: '2017-06-06',
    },
    {
      data: [{ imageUrl: 'image1_06-07' }, { imageUrl: 'image2_06-07' }],
      key: '2017-06-07',
    },
];

我很难确定如何深度推送每个data key的{​​{1}}。

如果重要allPosts实际上不仅仅是imageUrl,而且为了简单起见我删除了额外的数据。

3 个答案:

答案 0 :(得分:3)

我认为现在是时候学习如何使用mapfilterreduce,因为在更改数据结构时您将始终需要它们。这是使用reduce完成的非常干净的解决方案:

const postsByDate = allPosts.reduce((acc, post) => {
  const foundIndex = acc.findIndex(element => element.key === post.date);
  if (foundIndex === -1) {
    return [
      ...acc, 
      {
        key: post.date,
        data: [{imageUrl: post.imageUrl}],
      },
    ];
  }
  acc[foundIndex].data = [...acc[foundIndex].data, {imageUrl: post.imageUrl}];
  return acc;
}, []);

答案 1 :(得分:1)

这是你想要的吗?

const allPosts = [
    {
      date: '2017-06-06',
      imageUrl: 'image1_06-06',
    },
    {
      date: '2017-06-06',
      imageUrl: 'image2_06-06',
    },
    {
      date: '2017-06-07',
      imageUrl: 'image1_06-07',
    },
    {
      date: '2017-06-07',
      imageUrl: 'image2_06-07',
    }
];
var keys = [];
var PostsByDate = [];
for (var i in allPosts){
    var date = allPosts[i].date;
    var temp_img = [];
    for(var j in allPosts){
        if(allPosts[j].date == date){
          temp_img.push({imageUrl:allPosts[j].imageUrl});
        }
     }
     var obj = {data:temp_img,key:date};
     PostsByDate.push(obj);
} 
console.log(PostsByDate);

答案 2 :(得分:1)

试试这个

const allPosts = [
    {
        date: '2017-06-06',
        imageUrl: 'image1_06-06',
    },
    {
        date: '2017-06-06',
        imageUrl: 'image2_06-06',
    },
    {
        date: '2017-06-07',
        imageUrl: 'image1_06-07',
    },
    {
        date: '2017-06-07',
        imageUrl: 'image2_06-07',
    }
];


var o = {}
allPosts.map(item => {
    o[item.date] = o[item.date] || { key: item.date }
    if (o[item.date].data) {
        o[item.date].data.push({ imageUrl: item.imageUrl })
    } else {
        o[item.date].data = [{ imageUrl: item.imageUrl }]
    }
})

var PostByDate = Object.keys(o).map(val => {
    return o[val]
})

console.log(PostByDate)