如何在React Native中解析对象数组并从中创建一个新数组?

时间:2019-03-08 09:07:53

标签: react-native

我正处于反应本机的初学者阶段,试图从图像库中解析对象数组,我经历了多种解决方案,但遇到各种错误。

以下是选择图片后得到的json。

  

'use strict';

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'ap-southeast-2''});

// Create publish parameters
var params = {
    Message: 'This is a sample message',
    Subject: 'Test SNS From Lambda',
    TopicArn: 'arn:aws:sns:ap-southeast-2:577913011449:TestTopic'
};

module.exports.handler = async (event) => {

  // Create promise and SNS service object
  var publishTextPromise = new AWS.SNS().publish(params).promise();

  let response = {
      statusCode: 200,
      body: JSON.stringify('Hello from Lambda!'),
  };

  // Handle promise's fulfilled/rejected states
  return publishTextPromise.then(
      function(data) {
          console.log("Message ${params.Message} send sent to the topic ${params.TopicArn}");
          console.log("MessageID is " + data.MessageId);
          response.result = 'Success';
          return response;
      }).catch(
          function(err) {
          console.error(err, err.stack);
          response.result = 'Error';
          return response
      });

};

我一直在尝试的解决方案来自以下链接。

  

How to update array state in react native?

我尝试过的解决方案是

[
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-cefaffca-0fad-4b1a-aae5-1e7393a5da3f.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-d6052c1f-c075-47dc-a759-ff99d4d082a8.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-73537151-5f6c-4ece-9ee8-9e018b243ace.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:1048858,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-8ff9fe38-8050-447e-aea8-64976672fbef.jpg'
   }
]

我没有得到的是他们获得价值可变的地方。我需要在“路径”键之外创建一个数组。 以下是我的代码

    let markers = [...this.state.markers];
let index = markers.findIndex(el => el.name === 'name');
markers[index] = {...markers[index], key: value};
this.setState({ markers });

我打开选择器库的方法

 constructor(props){
    super(props);
    this.ShowPicker = this.ShowPicker.bind(this);
    this.createModal = this.createModal.bind(this);
    this.state = {date:"06/07/1988",valueInTens:0,valueInUnits:0,valueInFeet:0,valueInInches:0,checkedForKids:false,checkedForDrink:false,checkedForSmoke:false,filePath: {},dataForMaritalStatus:"",showSlider:false,language:"English"
  ,isModalVisible:false,checked:false,mImages:[] };
  }

这是我需要图像的地方

chooseFile = () => {
    var options = {
      title: 'Select Image',
      customButtons: [
        { name: 'customOptionKey', title: 'Choose Photo from Custom Option' },
      ],
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
    ImagePicker.openPicker({
  multiple: true
}).then(images => {

-> images // I need to create array out of this object



//  let markers = [...this.state.mImages];
// let index = markers.findIndex(images => images.name === 'path');
// markers[index] = {...markers[index], key: value};
// this.setState({ markers });
// let newMarkers = mImages.map(el => (
//       el.name==='name'? {...el, key: value}: el
// ))
//this.setState({ markers });
this.setState((mImages:images);
  console.log(images);
});

3 个答案:

答案 0 :(得分:0)

如果您想要一个仅包含数组中每个项目的路径变量的新数组,则应使用.map函数。

...
}).then(images => {
  const mImages = images.map(image => image.path);
  this.setState({mImages});
}

这将导致以下结果:

['http://foo.bar', 'http://bar.foo', ....]

答案 1 :(得分:0)

  

let pathArray = markers.map(function(item){return item.path;});

pathArray是arraylist

答案 2 :(得分:0)

arr = [
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-cefaffca-0fad-4b1a-aae5-1e7393a5da3f.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-d6052c1f-c075-47dc-a759-ff99d4d082a8.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:2097434,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-73537151-5f6c-4ece-9ee8-9e018b243ace.jpg'
   },
   {
      modificationDate:'1552035213000',
      size:1048858,
      mime:'image/jpeg',
      height:4608,
      width:2218,
      path:'file:///data/user/0/com.matrimonialapp/cache/react-native-image-crop-picker/image-8ff9fe38-8050-447e-aea8-64976672fbef.jpg'
   }
]
    var pathArr = [];
    arr.map((item) => {
        pathArr.push(item.path)
    })

pathArr是您需要创建的数组