Could someone help on how to loop over response while using substr to get each variable. The variables would be Amount, Type, Balance, Date.
I have the json response
[
[
"AmountTypeBalanceDate",
"$27.90Debit$6.3011/22/22, 3:32 PM",
"$30.00Credit$34.2011/22/22, 5:13 PM",
"$27.90Debit$4.209/12/22, 4:01 PM",
"$30.00Credit$32.109/12/22, 8:49 PM",
"$27.90Debit$2.107/20/22, 10:23 AM",
"$30.00Credit$30.007/20/22, 3:22 PM",
"Balance: $200.30"
]
]
Here is my code
if (xhr.status == 200) {
console.log("status 200");
var parsedWalletResult = JSON.parse(this.response);
console.log(parsedWalletResult.values[0][2]); //Get the second value
// Get the amount from the second
var walletAmount = parsedWalletResult.values[0][2]
walletAmount = walletAmount.substr(0, 5);
console.log("The wallet amount is: " + walletAmount);// The wallet amount is: $30.0
// loop over the parsed json response
for (const key in parsedWalletResult){
if(parsedWalletResult.hasOwnProperty(key)){
console.log(`${key} : ${parsedWalletResult[key]}`)
}
}
You cannot use substr() if the length of your fields differ ("Debit" vs "Credit"), at least not without hassle (i.e. trying out values until one matches).
You could use a regex though:
const data = [
[
"AmountTypeBalanceDate",
"$27.90Debit$6.3011/22/22, 3:32 PM",
"$30.00Credit$34.2011/22/22, 5:13 PM",
"$27.90Debit$4.209/12/22, 4:01 PM",
"$30.00Credit$32.109/12/22, 8:49 PM",
"$27.90Debit$2.107/20/22, 10:23 AM",
"$30.00Credit$30.007/20/22, 3:22 PM",
"Balance: $200.30"
]
]
const result = data.map(lines => lines.slice(1, -1).map(line => line.match(/(\$[0-9.]+)(\w+)(\$\d+\.\d{2})(.*)/).slice(1)))
console.log(result)
This is a perfect scenario for Regular Expressions. If you don't know regex, be careful, as this will be hard to maintain.
Here's my solution:
(possibly a more accurate regex than the other answer)
// I have removed the first and last elements so we just have data
const transactions = [
"$27.90Debit$6.3011/22/22, 3:32 PM",
"$30.00Credit$34.2011/22/22, 5:13 PM",
"$27.90Debit$4.209/12/22, 4:01 PM",
"$30.00Credit$32.109/12/22, 8:49 PM",
"$27.90Debit$2.107/20/22, 10:23 AM",
"$30.00Credit$30.007/20/22, 3:22 PM",
];
const transactionsAsObjects = transactions.map((transaction) => {
const pattern =
/(\$\d+\.\d+)(\w+)(\$\d+\.\d{2})(\d{1,2}?\/\d{1,2}\/\d{2}, \d{1,2}:\d{2} (AM|PM))/g;
const match = pattern.exec(transaction);
if (!match) return null;
return {
balance: match[1],
type: match[2],
amount: match[3],
date: match[4],
};
});
console.log(transactionsAsObjects);
/*
{balance: '$27.90', type: 'Debit', amount: '$6.30', date: '11/22/22, 3:32 PM'}
{balance: '$30.00', type: 'Credit', amount: '$34.20', date: '11/22/22, 5:13 PM'}
{balance: '$27.90', type: 'Debit', amount: '$4.20', date: '9/12/22, 4:01 PM'}
{balance: '$30.00', type: 'Credit', amount: '$32.10', date: '9/12/22, 8:49 PM'}
{balance: '$27.90', type: 'Debit', amount: '$2.10', date: '7/20/22, 10:23 AM'}
{balance: '$30.00', type: 'Credit', amount: '$30.00', date: '7/20/22, 3:22 PM'}
*/
Related
So basically i created a custom calendar for my doctor Appointement App that looks like this:
it displays the current week and date of the days.
till now those time slot are a static array that i made and rendered in a flatlist:
this.state = {
timeList: [
{ id: 1, time: "08:00 am" },
{ id: 2, time: "09:00 am" },
{ id: 3, time: "10:00 am" },
{ id: 4, time: "11:00 am" },
{ id: 5, time: "12:00 pm" },
{ id: 6, time: "01:00 pm" },
{ id: 7, time: "02:00 pm" },
{ id: 8, time: "03:00 pm" },
{ id: 9, time: "04:00 pm" },
{ id: 10, time: "05:00 pm" },
{ id: 11, time: "06:00 pm" },
{ id: 12, time: "07:00 pm" },
{ id: 13, time: "08:00 pm" }
]
};
and:
<FlatList
data={this.state.timeList}
renderItem={({ item, index }) => this.renderTimeData(item, index)}
keyExtractor={(item, index) => index.toString()}
/>
So my problem is i want to render the time from a fetched data in a way that take into consideration the the date of the day.for instance, here is a log of the data:
so from that attribut "date_start" i should make sure the date is matching in my calendar so i can display that "9:30"
Any idea how can I approach it?
i hope i made my self clear enough and thank you for your suggestions
You can simply use a library like Moment to identify the date & time of your object as below,
let date = moment("2020-03-23 09:30").format('YYYY-MM-DD');
console.log(date)
let time = moment("2020-03-23 09:30").format('h:mm A');
console.log(time)
For more information check String format of Moment.
Hope this helps you. Feel free for doubts.
If you want to allow the user to choose date and time for a day the official react-native documentation recommend you to use DateTimePicker
With this you will have the native component for rendering date in IOS and Android.
I have this kind of object
[
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:00 AM",
recipients: "junaid#evercam.io",
subject: "Your Scheduled SnapMail # 10:59"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "musaa#evercam.io",
subject: "Your Scheduled SnapMail # 11:05"
}
]
I am trying to do a search filter on this object in Vue, this object is designed as data: [] in the data part of Vue component.
What I am trying to do is to change the value of this.data on basis of the search query. For example, if my search string is jun then I only get one object which contains jun, I want to check this search string to each object's key and value.
I have tried this.
onFilterSet (filters) {
const oldData = this.data
let search = filters.search
if (search != null || search != "") {
this.data = this.data.filter((item) => {
return _.includes(item.recipients, search) || _.includes(item.camera_ids, search) || _.includes(item.camera_ids_failed, search) || _.includes(item.subject, search);
});
} else {
this.data = oldData
}
},
But this is not working. this.data value is not getting changed also not coming back to the old state when the search query is again empty. Please guide me.
UPDATE:
I am searching for anything, an example is: search string is: jun, I want to check it against camera_ids, camera_ids_failed, recipients, subject, if any of those key's values match jun, it should filter object and return it.
If the first object looks like this
[
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:00 AM",
recipients: "junaid#evercam.io",
subject: "Your Scheduled SnapMail # 10:59"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "musaa#evercam.io",
subject: "Your Scheduled SnapMail # 11:05"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "hibaa#evercam.io",
subject: "Your Scheduled Junaid # 11:05"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "hajraa#evercam.io",
subject: "Your Scheduled SnapMail # 11:05"
}
]
and search value is jun
The updated object after filter will be
[
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:00 AM",
recipients: "junaid#evercam.io",
subject: "Your Scheduled SnapMail # 10:59"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "hibaa#evercam.io",
subject: "Your Scheduled Junaid # 11:05"
}
]
Try this:
const data = [{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:00 AM",
recipients: "junaid#evercam.io",
subject: "Your Scheduled SnapMail # 10:59"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "musaa#evercam.io",
subject: "Your Scheduled SnapMail # 11:05"
}
]
new Vue({
el: '#app',
data() {
return {
data,
filtered: data,
term: ''
}
},
watch: {
term(val) {
this.filtered = this.data.filter(d => {
for (let name in d) {
if (d[name].toLowerCase().indexOf(val.toLowerCase()) > -1) {
return d;
}
}
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model="term" />
<pre>{{ filtered }}</pre>
</div>
You may like to use the reduce function and in its call back use for..in to iterate the object. Then use includes to check if the key's value contain the string, then push this object to the accumulator array.
This demo does not include case, so modify it according to case sensitivity.
let data = [{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:00 AM",
recipients: "junaid#evercam.io",
subject: "Your Scheduled SnapMail # 10:59 ,Test for jun"
},
{
camera_ids: "all",
camera_ids_failed: "failed",
inserted_at: "Monday, 25 Feb 2019 6:06 AM",
recipients: "musaa#evercam.io",
subject: "Your Scheduled SnapMail # 11:05"
}
]
function findObj(str) {
return data.reduce(function(acc, curr) {
for (let keys in curr) {
if (curr[keys].includes(str)) {
acc.push(curr)
}
}
return acc;
}, [])
}
console.log(findObj('jun'))
If you overwrite data with new values, you lose anything that is filtered out.
What you want is a computed property representing the filtered set of data. This will only compute if the data or search values change which makes it very efficient.
For example
data () {
return {
search: '',
data: [/* your array here */]
}
},
computed: {
filtered () {
if (!this.search) {
// empty search, return all values
return this.data
}
let normalizedSearch = this.search.toLowerCase()
return this.data.filter(datum => Object.values(datum).some(val =>
String(val).toLowerCase().includes(normalizedSearch)))
}
}
Then in your template
<input v-model="search">
<div v-for="item in filtered">
<!-- and so on -->
</div>
This question already has answers here:
How to sort an object array by date property?
(25 answers)
Closed 5 years ago.
I was having some problem to sort the date followed by time in descending order using JavaScript. Here is some inputs:
[{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}]
I wanted to sort them in descending order whereby the latest one will be on top but I not sure how to do it.
The desired output:
[{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"},
{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"}]
If the result comes from the same date, then I will sort according to time. Otherwise, the latest date will be on top. Any ideas?
Thanks!
Just concat the date and time, then parse it to a Date and get the timestamp. From then on, it's just plain old sorting.
const datetimes = [
{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}
]
const sorted = datetimes.sort((a, b) => {
const aDate = new Date(a.date + ' ' + a.time)
const bDate = new Date(b.date + ' ' + b.time)
return bDate.getTime() - aDate.getTime()
})
console.log(sorted)
Update: The linked answer in the comment by Marcel Gwerder indicates you could just skip getTime() altogether and just compare the Dates.
i am getting error when day is sunday.monday to saturday its working when day is sunday i am getting error
Error: Error while interpolating: {{isOpen(dealer.Day)}}
TypeError: Cannot read property 'replace' of undefined
var ds= 'Sun Dec 13 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
if you change day and date its working fine
var ds= 'Sat Dec 12 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
i have added my code below pls help me out.
angular.module('myApp', [])
.controller("myCntrl", function($scope, $filter) {
$scope.isOpen = function(dealerSchedule) {
var ds= 'Sun Dec 13 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
//var now = new Date();
//---if you change day and date you will not get error
//var ds= 'Sat Dec 12 2015 14:04:42 GMT+0530 (India Standard Time)';
//var now = new Date(ds);
var times = dealerSchedule[Object.keys(dealerSchedule)[now.getDay() - 1]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
var nowTime = new Date('1/1/1900 ' + now.toLocaleTimeString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
hour12: true
}));
console.log(nowTime);
var response = (times == "Leave" ? "Leave" : (nowTime >= new Date(times[0]) && nowTime <= new Date(times[1]) ? "Open Now" : "Closed Now"));
return response;
};
$scope.dealers = [{
S_Email_id: "aditiya#gmail.com ",
status: "",
Store_Name: "Adtiya Samsung Store",
Day: {
"monday": "09:10 AM - 06:30 PM",
"tuesday": "09:10 AM - 12:00 PM",
"wednesday": "09:10 AM - 06:30 PM",
"thursday": "09:10 AM - 06:30 PM",
"friday": "09:10 AM - 06:30 PM",
"saturday": "10:15 AM - 04:15 PM",
"sunday": "10:15AM - 04:15PM"
},
}, {
S_Email_id: "rajs#gmail.com",
status: "",
Store_Name: "sri shakthi mobile service",
Day: {
"monday": "09:00 AM - 06:00 PM",
"tuesday": "09:00 AM - 06:00 PM",
"wednesday": "09:00 AM - 06:00 PM",
"thursday": "09:00 AM - 06:00 PM",
"friday": "09:00 AM - 06:00 PM",
"saturday": "09:00AM - 06:00PM",
"sunday": "Leave"
},
}, {
S_Email_id: "sprtive23#gmail.com",
status: "",
Store_Name: "sun mobile service center ",
Day: {
"monday": "08:30 AM - 07:30 PM",
"tuesday": "02:30 PM - 07:30 PM",
"wednesday": "08:30 AM - 07:30 PM",
"thursday": "08:30 AM - 07:30 PM",
"friday": "08:30 AM - 07:30 PM",
"saturday": "08:15 AM - 02:15 PM",
"sunday": "8:15 AM - 12:15AM"
},
}, {
S_Email_id: "super#gmail.com ",
status: "",
Store_Name: "ragu mobile service center ",
Day: {
"monday": "10:00 AM - 10:00 PM",
"tuesday": "10:00 AM - 10:00 PM",
"wednesday": "10:00 AM - 04:00 PM",
"thursday": "10:00 AM - 10:00 PM",
"friday": "10:00 AM - 10:00 PM",
"saturday": "leave",
"sunday": "leave"
},
}]
//var date = new Date();
//$scope.hhmmsstt = $filter('date')(new Date(), 'hh:mm:ss a');
//console.log($scope.hhmmsstt);
})
//]]>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js'></script>
<div ng-app="myApp">
<div ng-controller="myCntrl">
<label>Search on Label</label>
<br>
<input ng-model="query" type="text" placeholder="Search for name" />
<br>
<br>
<div ng-repeat="dealer in dealers">
{{dealer.Store_Name}}
<br>{{dealer.S_Email_id}}
<br>{{dealer.Day}}
<br>
<input type="button" value="order" />
<span>{{isOpen(dealer.Day)}}</span>
<br>
<br>
<br>
</div>
</div>
</div>
check my code i am getting error
pls don't give down vote bcoze i dono why its not working i am new to technology.help me out
The problem is with
now.getDay() - 1 will fail for Sunday (getday() will return 0)
You should put a check for that like similar,
var dayCheck = now.getDay() == 0 ? 6 : now.getDay() - 1;
var times = dealerSchedule[Object.keys(dealerSchedule)[dayCheck]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
The error is coming from:
var times = dealerSchedule[Object.keys(dealerSchedule)[now.getDay() - 1]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
It's a bit confusing of what you are tying to achieve on this line?
Also as a note for future if you're going to put code into your questions removed commented out code as its not needed.
Also I'd consider upgrading you're angular version.
Issue with your code is in this statement
now.getDay() - 1
Days in Date object are zero based indices, so on Sunday, getDay() will return 0 and the above statement will evaluate to -1 which is a not valid index in your keys array of your Day object. To look up the day properly from date's getDay(), I suggest you use the index returned by getDay() and change your Day object so that sunday comes first and in sync with the spec like below.
Day: {
"sunday": "10:15AM - 04:15PM",
"monday": "09:10 AM - 06:30 PM",
"tuesday": "09:10 AM - 12:00 PM",
"wednesday": "09:10 AM - 06:30 PM",
"thursday": "09:10 AM - 06:30 PM",
"friday": "09:10 AM - 06:30 PM",
"saturday": "10:15 AM - 04:15 PM"
}
Also there are few inconsistencies in your JSON object for Day
Sometimes you used leave and sometimes its Leave. It should be same for all Day objects
For the 3rd dealer (sun mobile service center), you mentioned sunday timings as 8:15 AM - 12:15AM while it should be `8:15 AM - 12:15 PM' (from morning 8.15 - afternoon 12.15)
Correcting all these consistencies, adding some new logic for deriving dates from your Day object, here's a working Pen which will display Open Now / Closed Now / Leave accordingly.
Hope this helps :)
I have a variable that contains the following JSON string:
{
"0" : "Jun 20, 2012 03:02 PM",
"1" : "Jun 20, 2012 03:26 PM",
"2" : "Jun 21, 2012 01:12 PM",
"3" : "Jun 21, 2012 01:25 PM",
"4" : "Jun 21, 2012 02:42 PM",
"5" : "Jun 21, 2012 02:43 PM",
"6" : "NULL"
}
I wish to convert this JSON to an array in javascript such that
array[0] has "Jun 20, 2012 03:02 PM" array[1] has "Jun 20, 2012 03:26 PM" and so on.
You must parse your JSON string into a javascript object first.
JavaScript
var object = JSON.parse(JSONString);
To polyfill browsers without JSON support:
http://bestiejs.github.com/json3/
Then, convert that object to an array:
JavaScript
var arr = [];
for(var i in object) {
if(object.hasOwnProperty(i)) {
arr.push(object[i]);
}
}
jQuery
var arr = $.map(obj,function(value){ return value; });
Fiddle: http://jsfiddle.net/iambriansreed/MD3pF/
Note: Since the original poster did not mention jQuery it is worth mentioning that loading jQuery for only these instances isn't worthwhile, and you would be better off using the pure JavaScript if you aren't already using jQuery.
Alternatively, if you're targeting ES5 and above:
// myObject = { '0': 'a', '1': 'b' };
var myArray = Object.keys(myObject).map(function(key) { return myObject[key]; });
// myArray = [ 'a', 'b' ];
var currentVersion = {/literal} {$displayedVersion} {literal};
var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');