【问题标题】:How to turn an object into an array using map()?如何使用 map() 将对象转换为数组?
【发布时间】:2021-07-21 18:14:32
【问题描述】:

我有一个函数,捕获来自相机和画廊的图像,但是在选择图像或捕获照片时,我的函数返回对象时,我需要使用map(),以便它返回包含所有信息的数组图片的 URI 。在这种情况下我该如何实现 map()?

这是我的功能:

const [uriImg, setUriImg] = useState('');

function imagePickerCallback(data) {

if (data.didCancel) {
    return;
  }

  if (data.error) {
    return;
  }

  if (!data.uri) {
    return;
  }
  setUriImg(data);
  
}

这是我调用函数的地方

<Image 
    source = {{
    uri: uriImg
    ? uriImg.uri
    : 'https://socialistmodernism.com/wpcontent/uploads/2017/07/placeholder-image.png?w=640'}}
    style={styles.placeholderImage}
 />

      <View style={styles.optionsCamera}>
        <TouchableOpacity
          style={styles.button}
          onPress={() =>
          ImagePicker.launchCamera({},imagePickerCallback)
          }>
          <Text style={styles.buttonText}>Abrir câmera</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.button}
          onPress={() =>
          ImagePicker.launchImageLibrary({},imagePickerCallback)
          }>
          <Text style={styles.buttonText}>Escolher imagem</Text>
        </TouchableOpacity>
      </View>

这是在选择或捕获图像、对象时出现在控制台中的内容。

LOG {"assets": [{"fileName": "rn_image_picker_lib_temp_bbd3b196-997f-4227-80aa-f0d86824969a.jpg", "fileSize": 622543, "height": 2289, "type": "image/jpeg" , "uri": "file:///data/user/0/com.francaservices/cache/rn_image_picker_lib_temp_bbd3b196-997f-4227-80aa-f0d86824969a.jpg", "width": 2289}]}

【问题讨论】:

  • 如果你有一个 JS 对象,那么 .map() 不是一个函数。相反,我建议使用Object.entries(...)
  • 如何使用 Object.entries (...)?我是 react-native 新手,我真的不知道如何使用它。
  • 图像选择器一次只选择一个文件吗?如果是,试试这个setUriImg(data.assets[0].uri)
  • @Paloma 我会尝试发布答案

标签: javascript react-native


【解决方案1】:

JavaScript 对象类型没有.map() 函数。相反,您可以使用Object.entries(...) 遍历对象以获取键和值。有多种方法可以做到这一点:

data = {"assets": [{"fileName": "rn_image_picker_lib_temp_bbd3b196-997f-4227-80aa-f0d86824969a.jpg", "fileSize": 622543, "height": 2289, "type": "image/jpeg", "uri": "file:///data/user/0/com.francaservices/cache/rn_image_picker_lib_temp_bbd3b196-997f-4227-80aa-f0d86824969a.jpg", "width": 2289}]}
array = [] // A new array to store the values

// Assume 'data' is the object returned when an image is updated
Object.entries(data.assets[0]).forEach(([key, value]) => {
   array.push([key, value]); // Stores each key and value as an array pair
});

// Map over the new array printing out the keys and values
array.map(val => {console.log("Key:",val[0]+",","Value:",val[1])})

【讨论】:

  • 晚安,我尝试使用该代码,但没有成功。我需要从图库中选择图像或用相机拍照,我给出的图像只是一个例子。我使用了代码,但我仍然收到一个对象,我不知道我是否正确使用它。基本上,我可以拍照并选择图像,但是当我调用图像的 URI 时,它应该以数组而不是对象的形式出现,所以当我调用图像时,它不会在用户视觉上出现。
【解决方案2】:

仅通过以下方式解决:

data.assets[0]

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2017-12-24
相关资源
最近更新 更多