如何制作一个Object.map?

时间:2019-03-16 03:54:46

标签: react-native

我有一组数据。我使用了data.map的7个项目。我在firease上加载了这个数组,现在我不能这样称呼它。因为这不是对象中已经存在的数组。

问题。

如何为对象做data.map。而且,我需要传输数据。具体来说:id,name,info,latlng。里面是应该在data.map中的ImageCard。

示例对象:

Object {
  "0": Object {
    "id": 0,
    "image": "/images/Stargate.jpg",
    "info": "Stargate is a 1994 science fiction adventure film released through Metro-Goldwyn-Mayer (MGM) and Carolco Pictures..",
    "latlng": Object {
      "latitude": 53.6937,
      "longitude": -336.1968,
    },
    "name": "Stargate",
    "year": "1994",
  },

2 个答案:

答案 0 :(得分:0)

您可以使用Object.keys从Object中提取键,这将返回所有键的数组,然后映射该数组。

像这样

 const obj={
    "id": 0,
    "image": "/images/Stargate.jpg",
    "info": "Stargate is a 1994 science fiction adventure film released through Metro-Goldwyn-Mayer (MGM) and Carolco Pictures..",
    "latlng": Object {
      "latitude": 53.6937,
      "longitude": -336.1968,
    },
    "name": "Stargate",
    "year": "1994",
  }

  let keys = Object.keys(obj);
  keys.map(item=>{
    //..... do your stuff from object like,
  let y=obj[item]
   //  or whatever
  }

答案 1 :(得分:0)

多种方法 Jaydeep Galani提到的一个

另一种方法是使用代理

const obj={
"id": 0,
"image": "/images/Stargate.jpg",
"info": "Stargate is a 1994 science fiction adventure film released through 
   Metro-Goldwyn-Mayer (MGM) and Carolco Pictures..",
"latlng": Object {
  "latitude": 53.6937,
  "longitude": -336.1968,
},
"name": "Stargate",
"year": "1994",
}
 const newObj = new Proxy(obj,{
 get: (target, prop)=>{
  let newArr = [];
  if(prop === 'map'){
   // then first convert target into array 
   Object.keys(target).foreach(item => {
     newArr.push({item:target[item]})
     })


   // then apply map function to that and return the result
    return newArr.map((item)=>{
   //your code goes here like
   return<div>{item.info}</div>
    })

    }
   }

  })