Vue.Js - How to parse integer array object data - arrays

I've a response data in array object
here my response code :
{
"data": [
{
"id": 7,
"product_name": "iPad",
"rating": "4.00"
},
{
"id": 2,
"product_name": "iPhone",
"rating": "3.00"
},
{
"id": 8,
"product_name": "iPod",
"rating": "7.00"
},
{
"id": 4,
"product_name": "iMac",
"rating": "9.00"
}
],
"status": 200,
"error": 0
}
and then i try to map the array object to parse the data 'rating' to integer, here my axios code :
getCustomerType: function(store) {
this.loading = true
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
axios({
method: 'GET',
url: baseApi(this.selectedStore.url_id, 'en', 'customertype'),
params: this.params,
headers: headers
})
.then(response => {
this.customerTypeData = response.data.data
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
this.loading = false
})
}
But the code of parseInt it doesn't make it solve
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
Expected :
rating (by index) it change from string to number by index array

Related

I can't use filter when I have objects inside an array and find last id, angular

I need your opinion in this situation:
I get from API with this function:
getRS(
idProject: string
): Observable<ResponseModel<RSModel>> {
return this.http.get<ResponseModel<RSModel>>(
ApiUrlsConfig.getRS(
idProject
)
);
}
this response:
{
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3",
}
],
"result": null
}
I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
#Input() set jobId(jobId: string) {
this.optionsService
.getRS(
this.idProject
)
.pipe()
.subscribe((res) => {
let resId = res.filter((aaa)=>{
if(aaa.id === jobId){
res.slice(-1)[0].id
}
}
)
});
}
Not function.
Please can you share with me any idea?
Thank you
Try this logic:
Loop backwards throw it.
Loop backwards over index to the start.
Splice duplicates.
let response = {
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3"
}
],
"result": null
}
let data = response.data;
for (let i = data.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
data.splice(j, 1);
j++;
}
}
};
console.log(data);
try this:
if(aaa.id == jobId){
return res.slice(-1)[0].id
}

firestore is rejecting post request from angularjs

i'm trying to add a new document to the collection Offers by using $http.post method in angularjs.
i'm getting this error in the console:
Possibly unhandled rejection: {
"data": {
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\nfields%5BcompanyName\n^",
"status": "INVALID_ARGUMENT"
}
},
"status": 400,
"config": {
"method": "POST",
"transformRequest": [null],
"transformResponse": [null],
"jsonpCallbackParam": "callback",
"url": "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers",
"data": "fields%5BcompanyName%5D=qwe&fields%5Bdescription%5D=qwe&fields%5BexpiredDate%5D=qwe&fields%5Btitle%5D=qwe&fields%5BuserId%5D=rsVWKar7UTMwUmcyYJbr6Rif4NN2",
"headers": {
"Content-Type": "application/json; charset=UTF-8;",
"Accept": "application/json, text/plain, /"
}
},
"statusText": "",
"xhrStatus": "complete"
}
i have tried so many solutions but none worked.
here's the controller code:
app.controller('insert_controller', function ($scope, $http, $httpParamSerializerJQLike) {
let userId = "rsVWKar7UTMwUmcyYJbr6Rif4NN2";
let url = "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers";
$scope.insertOffer = function () {
let companyName = $scope.companyName;
let title = $scope.title;
let expiredDate = $scope.expiredDate;
let description = $scope.description;
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': 'application/json; charset=UTF-8;'
}
}).then(function (res) {
if (res.data){
$scope.companyName = null;
$scope.title = null;
$scope.expiredDate = null;
$scope.description = null;
alert('Offer Added Successfully')
}
}).catch(function (err) {
console.log(err);
throw err
});
}
});
any help would be great, thanks in advance
EDIT: i tried sending a post request from postman and it worked to the same url and the same json data structure i'm using
the problem was that I was using a wrong schema.
This is the old schema:
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
This is the correct schema which worked:
let data = {
"fields": {
"companyName": {
"stringValue": companyName
},
"title": {
"stringValue": title
},
"expiredDate": {
"stringValue": expiredDate
},
"description": {
"stringValue": description
},
"userId": {
"stringValue": userId
},
}
};

How to get a record from an array result of API in React Native with condition?

This is the result JSON file from API:
{
"data": [
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "govid",
"filename": "gov_id.png",
"path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
"ext": ".png",
"posted_dt": "12/11/2019 10:38:20 AM"
},
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "compid",
"filename": "compid.jpg",
"path": "C:\\MOBILEAPP\\compid/cid.jpg",",
"ext": ".jpg",
"posted_dt": "12/11/2019 10:38:20 AM"
}
],
"error_message": "Successfully retrieved.",
"is_success": true,
"requested_on": "12/18/2019 2:14:27 PM"
}
I need to get the path where tag = 'govid' to be puth in a variable because it is used in the header of another API fetching.
async getProfilePhotoPath(token) {
//membid is recordid
let membid = await AsyncStorage.getItem(MEMBER_ID);
let resp2 = await fetch("https://api/files",
{
method: 'GET',
headers: {
"Authorization": "Bearer " + token,
"MemberID": membid,
'Content-Type': 'application/json;charset=UTF-8',
},
},
)
.then(resp2 => {
let respImg = resp2.json();
varImagePath = "should contain data.path where tag = 'govid'"
console.log('This is respImg values',respImg)
return respImg;
})
.catch(error => {
alert('Error in resp2 imgpath!' + error);
});
}
async getProfilePhoto() {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
this.getProfilePhotoPath(token);
let resp = await fetch("https://api/filepathtoimage", {
headers: {
"Authorization": "Bearer " + token,
"ImagePath": varImagePath,
}
})
let respBlob = await resp.blob();
let reader = new FileReader()
reader.readAsDataURL(respBlob)
reader.onload = () => {
this.setState({ imgsrc: reader.result })
}
}
console.log('This is respImg values',respImg) returns:
This is respImg values
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40: 1
_65: 1
_55:
data: Array(2)
0: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "govid", filename: "gov_id.png", path: "C:\\MOBILEAPP\\governmentid/gov_id.png", …}
1: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "compid", filename: "compid.jpg", path: "C:\\MOBILEAPP\\compid/cid.jpg", …}
length: 2
__proto__: Array(0)
error_message: "Successfully retrieved."
is_success: true
requested_on: "12/18/2019 3:10:32 PM"
__proto__: Object
_72: null
__proto__: Object
How to I put value on varImagePath (in this example should be 'C:\MOBILEAPP\governmentid/gov_id.png')?
resp2.json() return a promise.
.then(resp2 => resp2.json())
.then(jsonObject => {
const data = jsonObject.data;
const record = data.find(item => item.tag === 'govid');
if (record) {
varImagePath = record.path;
}
})
Just use filter:
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
An example:
let arr = [
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "govid",
"filename": "gov_id.png",
"path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
"ext": ".png",
"posted_dt": "12/11/2019 10:38:20 AM"
},
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "compid",
"filename": "compid.jpg",
"path": "C:\\MOBILEAPP\\compid/cid.jpg",
"ext": ".jpg",
"posted_dt": "12/11/2019 10:38:20 AM"
}
]
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
console.log(result);
UPDATE:
In your response:
then(resp2 => {
let respImg = resp2.json();
let arr = respImg.data;
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
return respImg;
})

setItem in AsyncStorage doesn't work

I'm trying to upload some data to the server from React Native. The data is stored in AsyncStorage.
The data is as follows :
let vehicles = [
{
"id": 1,
"make_text": "Peugeot",
"model_text": "208",
"color_text": "Argent",
"category_text": "CT",
"tag_text": "",
"vin": "123456",
"registration": "",
"reference": "",
"comment": "",
"autralis_id": 151390
},
{
"id": 1,
"make_text": "Peugeot",
"model_text": "307",
"color_text": "Bleu",
"category_text": "CT",
"tag_text": "",
"vin": "654321",
"registration": "",
"reference": "",
"comment": "",
"autralis_id": 156413
}
]
And
let vehicle_slots = [
{
"vehicle_id": 1,
"slot_id": 118,
"area": "",
"zone": "B",
"aisle": "",
"side": "S",
"col": 2,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "0a016bb9-b7bb-4dd7-a0bf-407ef31a0c1a",
"reason": "ENTER",
"handled": 0,
"uploaded": 0
},
{
"vehicle_id": 1,
"slot_id": 2521,
"area": "",
"zone": "C",
"aisle": "",
"side": "E",
"col": 4,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "64c726e2-37ec-4ab7-8b57-b08e9899086a",
"reason": "ENTER",
"handled": 0,
"uploaded": 0
}
]
I want to send only those which have uploaded and handled property equals to 0.
Thus, first I get those values where uploaded and handled property is equal to 0. I do it as follows:
try {
let vehicle_data = await AsyncStorage.getItem('vehicle');
if (vehicle_data !== null){
// We have data!!
let vehicle_slot_data = await AsyncStorage.getItem('vehicle_slot');
if (vehicle_slot_data !== null){
vehicle_data = JSON.parse(vehicle_data);
vehicle_slot_data = JSON.parse(vehicle_slot_data);
let result_to_handle = [];
let result_to_upload = [];
vehicle_slot_data.forEach(v => {
let not_handled = vehicle_data.find(m => m.id === v.vehicle_id && v.handled === 0);
let not_uploaded = vehicle_data.find(m => m.id === v.vehicle_id && v.uploaded === 0);
if ( not_uploaded ) result_to_upload.push(that.renderData(v, not_uploaded)[0]);
if ( not_handled ) result_to_handle.push(that.renderData(v, not_handled)[0]);
});
//Here I have result_to_handle and result_to_upload with the data that I need to send to the server.
............
If result_to_handle and result_to_upload have length > 0 then I want to send them to the server and update the property handled and property uploaded to 1 in AsyncStorage.
I try to do it as follows :
..............
if (result_to_handle.length > 0){
let options = {
method: 'POST',
body: JSON.stringify(result_to_handle),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
fetch(data_url + "/manager/transport/sync/movements/", options)
.then(response => response.json())
.then(responseData => {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
let data = [];
if (json) data = JSON.parse(json);
let result = [];
forEach(data, value => {
if( value.handled === 0 ){
value.handled = 1;
result.push(value);
}else{
result.push(value);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result))
});
});
}
if (result_to_upload.length > 0){
forEach(result_to_upload, value => {
if (value.picturepath) {
let body = new FormData();
const photo = {
uri: value.picturepath,
type: 'image/jpeg',
name: value.pictureguid + '.jpg',
};
body.append('image', photo);
let xhr = new XMLHttpRequest();
xhr.open('POST', data_url + "/manager/transport/sync/picture/?pictureguid=" + value.pictureguid);
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
if (json){
let data = JSON.parse(json);
let result_data = [];
forEach(data, val => {
if( val.pictureguid === value.pictureguid ){
val.uploaded = 1;
result_data.push(val);
}else{
result_data.push(val);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_data), () => s_cb())
}
});
}
}
};
xhr.onerror = (e) => console.log('Error');
xhr.send(body);
} else {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
if (json){
let data = JSON.parse(json);
let result_data = [];
forEach(data, val => {
if( val.pictureguid === value.pictureguid ){
val.uploaded = 1;
result_data.push(val);
}else{
result_data.push(val);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_data), () => s_cb())
}
});
}
});
}
But the result that I get is not correct.
The vehicle_slot from AsyncStorage is as follows:
[
{
"vehicle_id": 1,
"slot_id": 118,
"area": "",
"zone": "B",
"aisle": "",
"side": "S",
"col": 2,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "0a016bb9-b7bb-4dd7-a0bf-407ef31a0c1a",
"reason": "ENTER",
"handled": 1,
"uploaded": 0
},
{
"vehicle_id": 1,
"slot_id": 2521,
"area": "",
"zone": "C",
"aisle": "",
"side": "E",
"col": 4,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "64c726e2-37ec-4ab7-8b57-b08e9899086a",
"reason": "ENTER",
"handled": 1,
"uploaded": 1
}
]
Thus, for the first object is the value uploaded still equal to 0 but it should be equal to 1.
Any advice?

How to map json data with array in react native

I have array like this in react native
const data = [
{ key: 1, label: 'Service1'},
{ key: 2, label: 'Service2' },
{ key: 3, label: 'Service3' },
{ key: 4, label: 'Service4' },
{ key: 5, label: 'Service4' },
];
and json data:
"services": [
{
"id": 1,
"name": "Hotels",
},
{
"id": 2,
"name": "Embassies",
},
]
How to map id to key and name to label???
You want to fill your const data with values from JSON, correct?
Try this:
var jsonData = {
"services": [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
]
};
var data = jsonData.services.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
if your data like below (removed services key)
var jsonData = [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
];
var data = jsonData.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
i know it to much late,but i hope its helpfull for others,How to fetch the response of JSON array in react native?How to map json data with array in react native
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
PickerSelectedVal : '',
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
render() {
return (
<Picker
selectedValue={this.state.PickerSelectedVal}
placeholder="Select your customer"
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >
{this.state.accountnameMain.map((item, key)=>(
<Picker.Item label={item} value={item} key={key}/>)
)}
</Picker>
)
}
}
the above example is fetch array of data from json,and map data in to dropdown/picker,i hope its helpfull for others,if you have any query, asked from me

Resources