Javascript filter with regex on JSON - javascript

This is a follow on from a previous question I had that I got an answer for.
Original Question with Answer: Replicate an SQL query in javascript or jquery
This time I'm trying to find a specific set of words in the comment, I can pull out the records but it's not pulling the records with more words than it's looking for.
Array:
[
{
"transaction_id": "44b36e13-ba02-42a6-8b3a-82f6096ec3ba",
"timestamp": "2021-03-03 18:28:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Winston Bolt",
"account_id": "61408386"
},
{
"transaction_id": "6482c419-ff8c-4121-98ae-6f2437646ba8",
"timestamp": "2021-03-03 17:46:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Winston Bolt",
"account_id": "61453979"
},
{
"transaction_id": "0ab6c0cd-4389-4848-92f2-60b54982d5c7",
"timestamp": "2021-03-03 17:42:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Winston Bolt",
"account_id": "61428024"
},
{
"transaction_id": "11580df3-6403-4cf9-a8b0-38b8b1b1b25f",
"timestamp": "2021-03-03 17:28:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Erin Cox",
"account_id": "61342083"
},
{
"transaction_id": "3c6f93e5-ce24-405b-9558-44b2bf3f3653",
"timestamp": "2021-03-03 17:26:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Ai Musori",
"account_id": "61712295"
},
{
"transaction_id": "a14712a0-8808-4686-99b2-ed9639d61fbc",
"timestamp": "2021-03-03 15:15:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Ai Musori",
"account_id": "61977423"
},
{
"transaction_id": "def6ac07-6a7a-48c4-8534-0c68e8ddc46b",
"timestamp": "2021-03-03 09:06:00",
"direction": "incoming",
"type": "transfer",
"change": "999",
"comment": "Business Payment: Storefront Restock x1100",
"requestor": "Sean Tinker",
"account_id": "61747726"
},
{
"transaction_id": "f57432d0-b744-41ef-b6b8-af77b81b17ec",
"timestamp": "2021-03-03 08:59:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: renewal",
"requestor": "Sarah Ableton",
"account_id": "61171658"
},
{
"transaction_id": "ddcd5fd0-78c2-4e80-a603-09acb589122d",
"timestamp": "2021-03-03 07:22:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Sean Tinker",
"account_id": "61111782"
},
{
"transaction_id": "7e359364-666d-41b3-a2cd-86ffac82e0a1",
"timestamp": "2021-03-03 03:53:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership Renewal",
"requestor": "Donovan King",
"account_id": "61252737"
},
{
"transaction_id": "448fefc0-4c35-48e4-b9ee-e2ab4e31b8aa",
"timestamp": "2021-03-03 02:30:00",
"direction": "incoming",
"type": "transfer",
"change": "999",
"comment": "Business Payment: Storefront Restock",
"requestor": "Donovan King",
"account_id": "61994863"
},
{
"transaction_id": "a4417a9c-fbd6-4b2d-8294-244e35dd7774",
"timestamp": "2021-03-03 02:27:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Renewal",
"requestor": "Donovan King",
"account_id": "61773626"
},
{
"transaction_id": "4b294212-9451-4bc8-8950-3810c7e59765",
"timestamp": "2021-03-06 12:24:00",
"direction": "incoming",
"type": "purchase",
"change": "999",
"comment": "Business Services Payment: Membership",
"requestor": "Gomer Colton",
"account_id": "61267568"
},
{
"transaction_id": "e827c214-cab2-48e7-8367-8061ed633988",
"timestamp": "2021-03-04 01:41:00",
"direction": "outgoing",
"type": "transfer",
"change": "20000",
"comment": "Cassie car down payment",
"requestor": "Dean Watson",
"account_id": "61209808"
},
{
"transaction_id": "47c64f4b-3196-477d-a336-be4fca4903b1",
"timestamp": "2021-03-04 01:41:00",
"direction": "outgoing",
"type": "transfer",
"change": "20",
"comment": "Cassie car down payment",
"requestor": "Dean Watson",
"account_id": "61209808"
},
{
"transaction_id": "b8833152-c541-40f9-b7cc-cfb6dc51cd02",
"timestamp": "2021-03-03 15:24:00",
"direction": "outgoing",
"type": "transfer",
"change": "100",
"comment": "Employee Payment: Expemses",
"requestor": "Dean Watson",
"account_id": "61762557"
},
{
"transaction_id": "3bf5298b-7411-4180-adeb-72abfa2bb903",
"timestamp": "2021-03-03 00:30:00",
"direction": "incoming",
"type": "withdraw",
"change": "10000",
"comment": "",
"requestor": "Otto Delmar",
"account_id": "64397152"
},
{
"transaction_id": "cd394900-23c5-4130-86ca-a55671b3963c",
"timestamp": "2021-03-02 20:26:00",
"direction": "incoming",
"type": "transfer",
"change": "999",
"comment": "Business Payment: Storefront Restock x4500 # 16",
"requestor": "Marlo Stanfield",
"account_id": "61752944"
},
{
"transaction_id": "d99042fa-ca26-4326-aa5d-5a8aafa1fce0",
"timestamp": "2021-03-02 20:21:00",
"direction": "outgoing",
"type": "deposit",
"change": "20000",
"comment": "Business Payment: Bullshit fine coverage",
"requestor": "Dean Watson",
"account_id": "61762557"
}
]
Example:
In this case the Array is in the data
var restock_string = 'Business Payment: Storefront Restock';
// Filter out transfers only
const transfer_filter = data.filter(o => o['type'] === 'transfer')
// Filter out transfers for restock reimbursments
const restock_filter = transfer_filter.filter(o =>
o['comment'].toLowerCase() === restock_string.toLowerCase())
This case works fine as long as there is no other characters in the comment. Unfortunately people can't follow direction and add quotes or extra info to the line and it gets missed when parsed. I made a regex that just looks for the words "Storefront Restock" but I can't figure out how to use it with the filter.
Regex:
/(Storefront) (Restock)/gi

Use RegExp#test:
transfer_filter.filter(o => /Storefront Restock/i.test(o.comment))

Something like that ?
let rx= new RegExp('(?=.*Storefront)(?=.*Restock)','i' )
let filterElms = data.filter( ({type,comment})=> type==='transfer' && rx.test(comment))
const data =
[ { transaction_id : '44b36e13-ba02-42a6-8b3a-82f6096ec3ba'
, timestamp : '2021-03-03 18:28:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Winston Bolt'
, account_id : '61408386'
}
, { transaction_id : '6482c419-ff8c-4121-98ae-6f2437646ba8'
, timestamp : '2021-03-03 17:46:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Winston Bolt'
, account_id : '61453979'
}
, { transaction_id : '0ab6c0cd-4389-4848-92f2-60b54982d5c7'
, timestamp : '2021-03-03 17:42:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Winston Bolt'
, account_id : '61428024'
}
, { transaction_id : '11580df3-6403-4cf9-a8b0-38b8b1b1b25f'
, timestamp : '2021-03-03 17:28:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Erin Cox'
, account_id : '61342083'
}
, { transaction_id : '3c6f93e5-ce24-405b-9558-44b2bf3f3653'
, timestamp : '2021-03-03 17:26:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Ai Musori'
, account_id : '61712295'
}
, { transaction_id : 'a14712a0-8808-4686-99b2-ed9639d61fbc'
, timestamp : '2021-03-03 15:15:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Ai Musori'
, account_id : '61977423'
}
, { transaction_id : 'def6ac07-6a7a-48c4-8534-0c68e8ddc46b'
, timestamp : '2021-03-03 09:06:00'
, direction : 'incoming'
, type : 'transfer'
, change : '999'
, comment : 'Business Payment: Storefront Restock x1100'
, requestor : 'Sean Tinker'
, account_id : '61747726'
}
, { transaction_id : 'f57432d0-b744-41ef-b6b8-af77b81b17ec'
, timestamp : '2021-03-03 08:59:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: renewal'
, requestor : 'Sarah Ableton'
, account_id : '61171658'
}
, { transaction_id : 'ddcd5fd0-78c2-4e80-a603-09acb589122d'
, timestamp : '2021-03-03 07:22:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Sean Tinker'
, account_id : '61111782'
}
, { transaction_id : '7e359364-666d-41b3-a2cd-86ffac82e0a1'
, timestamp : '2021-03-03 03:53:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership Renewal'
, requestor : 'Donovan King'
, account_id : '61252737'
}
, { transaction_id : '448fefc0-4c35-48e4-b9ee-e2ab4e31b8aa'
, timestamp : '2021-03-03 02:30:00'
, direction : 'incoming'
, type : 'transfer'
, change : '999'
, comment : 'Business Payment: Storefront Restock'
, requestor : 'Donovan King'
, account_id : '61994863'
}
, { transaction_id : 'a4417a9c-fbd6-4b2d-8294-244e35dd7774'
, timestamp : '2021-03-03 02:27:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Renewal'
, requestor : 'Donovan King'
, account_id : '61773626'
}
, { transaction_id : '4b294212-9451-4bc8-8950-3810c7e59765'
, timestamp : '2021-03-06 12:24:00'
, direction : 'incoming'
, type : 'purchase'
, change : '999'
, comment : 'Business Services Payment: Membership'
, requestor : 'Gomer Colton'
, account_id : '61267568'
}
, { transaction_id : 'e827c214-cab2-48e7-8367-8061ed633988'
, timestamp : '2021-03-04 01:41:00'
, direction : 'outgoing'
, type : 'transfer'
, change : '20000'
, comment : 'Cassie car down payment'
, requestor : 'Dean Watson'
, account_id : '61209808'
}
, { transaction_id : '47c64f4b-3196-477d-a336-be4fca4903b1'
, timestamp : '2021-03-04 01:41:00'
, direction : 'outgoing'
, type : 'transfer'
, change : '20'
, comment : 'Cassie car down payment'
, requestor : 'Dean Watson'
, account_id : '61209808'
}
, { transaction_id : 'b8833152-c541-40f9-b7cc-cfb6dc51cd02'
, timestamp : '2021-03-03 15:24:00'
, direction : 'outgoing'
, type : 'transfer'
, change : '100'
, comment : 'Employee Payment: Expemses'
, requestor : 'Dean Watson'
, account_id : '61762557'
}
, { transaction_id : '3bf5298b-7411-4180-adeb-72abfa2bb903'
, timestamp : '2021-03-03 00:30:00'
, direction : 'incoming'
, type : 'withdraw'
, change : '10000'
, comment : ''
, requestor : 'Otto Delmar'
, account_id : '64397152'
}
, { transaction_id : 'cd394900-23c5-4130-86ca-a55671b3963c'
, timestamp : '2021-03-02 20:26:00'
, direction : 'incoming'
, type : 'transfer'
, change : '999'
, comment : 'Business Payment: Storefront Restock x4500 # 16'
, requestor : 'Marlo Stanfield'
, account_id : '61752944'
}
, { transaction_id : 'd99042fa-ca26-4326-aa5d-5a8aafa1fce0'
, timestamp : '2021-03-02 20:21:00'
, direction : 'outgoing'
, type : 'deposit'
, change : '20000'
, comment : 'Business Payment: Bullshit fine coverage'
, requestor : 'Dean Watson'
, account_id : '61762557'
}
]
let rx= new RegExp('(?=.*Storefront)(?=.*Restock)','i' )
let filterElms = data.filter( ({type,comment})=> type==='transfer' && rx.test(comment))
console.log( filterElms )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

Related

How remove data from an array in aggrigation whithout disturbing outside data in mongodb

Here I am trying to get entire data but if date less then current then do not fetch that date from the database.
{
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab5"),
"highlights" : [
"highlights-1",
],
"notes" : [
"Listen"
],
"soldout" : false,
"active" : false,
"operator" : ObjectId(""),
"title" : "2D1N Awesome trip to Knowhere 99",
"destinations" : [
{
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab6"),
}
],
"difficulty" : "Easy",
"duration" : {
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab7"),
"days" : NumberInt(2),
"nights" : NumberInt(1)
},
"media" : {
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab8"),
"images" : [
],
"videos" : [
]
},
"description" : "Surrounded ",
"inclusions" : [
{
"_id" : ObjectId(""),
"text" : "Included"
}
],
"itinerary" : "Surrounded .",
"thingsToCarry" : [
{
"_id" : ObjectId(""),
"text" : "Yourself"
}
],
"exclusions" : [
{
"_id" : ObjectId(""),
"text" : "A Lot"
}
],
"policy" : "Fully refundable 7777 Days before the date of Experience",
"departures" : [
{
"dates" : [
ISODate("2019-11-19T02:44:58.989+0000"),
ISODate("2019-11-23T17:19:47.878+0000")
],
"_id" : ObjectId(""),
"bookingCloses" : "2 Hours Before",
"maximumSeats" : NumberInt(20),
"source" : {
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac2"),
"code" : "code",
"name" : "Manali",
"state" : "Himachal Pradesh",
"region" : "North",
"country" : "India",
"coordinates" : [
23.33,
NumberInt(43),
NumberInt(33)
]
},
"pickupPoints" : [
{
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac3"),
"name" : "name-3",
"address" : "address-3",
"time" : "time-3",
"coordinates" : [
23.33,
NumberInt(43),
NumberInt(33)
]
}
],
"prices" : {
"3" : NumberInt(5)
},
"mrps" : {
"3" : NumberInt(5)
},
"markup" : NumberInt(25),
"discount" : NumberInt(0),
"b2m" : {
"3" : NumberInt(5)
},
"m2c" : {
"3" : 6.25
},
"minimumOccupancy" : NumberInt(3),
"maximumOccupancy" : NumberInt(3)
}
],
"bulkDiscounts" : [
{
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac4")
}
],
}
In this I am trying to get all the data except the date section should be different. Means I should get my output as below
{
"_id": "5d6fad0f9e0dc027fc6b5ab5",
"highlights": [
"highlights-1",
"highlights-2",
"highlights-3",
"highlights-4",
"highlights-5"
],
"notes": [
"Listen"
],
"soldout": false,
"active": false,
"operator": "5d5d84e8c89fbf00063095f6",
"title": "2D1N Awesome trip to Knowhere 99",
"destinations": [
{
"code": "code",
"name": "Manali",
"coordinates": [
23.33,
43,
33
]
}
],
"difficulty": "Easy",
"duration": {
"_id": "5d6fad0f9e0dc027fc6b5ab7",
"days": 2,
"nights": 1
},
"media": {
"_id": "5d6fad0f9e0dc027fc6b5ab8",
"images": [
],
"videos": []
},
"description": "Surrounded.",
"inclusions": [
{
"_id": "5d6fad0f9e0dc027fc6b5abe",
"text": "Included"
}
],
"itinerary": "Surrounded",
"thingsToCarry": [
{
"_id": "5d6fad0f9e0dc027fc6b5abf",
"text": "Yourself"
}
],
"exclusions": [
{
"_id": "5d6fad0f9e0dc027fc6b5ac0",
"text": "A Lot"
}
],
"policy": "Fully refundable 7777 Days before the date of Experience",
"departures": [
{
"dates": [
"2019-11-23T17:19:47.878Z"
],
"_id": "5d6fad0f9e0dc027fc6b5ac1",
"bookingCloses": "2 Hours Before",
"maximumSeats": 20,
"source": {
"code": "code",
"name": "Manali",
"coordinates": [
23.33,
43,
33
]
},
"pickupPoints": [
{
"coordinatesType": "Point",
"_id": "5d6fad0f9e0dc027fc6b5ac3",
"name": "name-3",
"address": "address-3",
"time": "time-3",
"coordinates": [
23.33,
43,
33
]
}
],
"mrps": {
"3": 5
},
"markup": 25,
"discount": 0,
"b2m": {
"3": 5
},
"m2c": {
"3": 6.25
},
"minimumOccupancy": 3,
"maximumOccupancy": 3
}
],
"bulkDiscounts": [
{
"_id": "5d6fad0f9e0dc027fc6b5ac4"
}
],
"url": "",
}
]
I mean to say that no difference in output except dates array. If dates are less than current date then no need to fetch else fetch from DB with filtered dates array.
If you use mongo 3.4> then you can try with $addFields and $filter:
myCollection.aggregate([
{$match: {
'departures.dates': {
$elemMatch: {$gt: new Date()}}
}
},
{$addFields: {
'departures.dates': {
$filter: {
input: '$departures.dates',
as: 'date',
cond: {
$gt: ['$$date', new Date()]
}
}
}
}}
])
I was missing one terms here that my documnet structure is like below
{
_id: ObjecId(),
departure: [{
dates: [Array]
}]
}
So, here is my solution in the below code
pipeline = [
{ $unwind: '$departures' },
{
$addFields: {
'departures.dates': {
$filter: {
input: '$departures.dates',
as: 'date',
cond: {
$gt: ['$$date', new Date()]
}
}
}
}
}
];

Output formatted json to a console.log

I have ajax which brings me back json,
What I want is to output everything inside 'routes' to a console.log but I don't know how to do that.
This is json output:
{
"geocoded_waypoints": [
{
"geocoder_status": "OK",
"place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
"types": [
"premise"
]
},
{
"geocoder_status": "OK",
"place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
"types": [
"premise"
]
}
],
"routes": [
{
"bounds": {
"northeast": {
"lat": 53.541228,
"lng": -2.1114936
},
"southwest": {
"lat": 53.5406464,
"lng": -2.1120657
}
},
"copyrights": "Dane do Mapy ©2017 Google",
"legs": [
{
"distance": {
"text": "0,1 km",
"value": 112
},
"duration": {
"text": "1 min",
"value": 27
},
"end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"start_address": "Ashton Arms, Oldham, Wielka Brytania",
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"steps": [
{
"distance": {
"text": "39 m",
"value": 39
},
"duration": {
"text": "1 min",
"value": 7
},
"end_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
"polyline": {
"points": "egxeIxk{KEBEDADAF?H#JJr#"
},
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "52 m",
"value": 52
},
"duration": {
"text": "1 min",
"value": 11
},
"end_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
"maneuver": "turn-left",
"polyline": {
"points": "ggxeIzn{KxAk#"
},
"start_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "21 m",
"value": 21
},
"duration": {
"text": "1 min",
"value": 9
},
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
"maneuver": "turn-right",
"polyline": {
"points": "mdxeInm{KJ|#"
},
"start_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"travel_mode": "DRIVING"
}
],
"traffic_speed_entry": [],
"via_waypoint": []
}
],
"overview_polyline": {
"points": "egxeIxk{KKHCL#TJr#xAk#J|#"
},
"summary": "Ascroft St i Harrison St",
"warnings": [],
"waypoint_order": []
}
],
"status": "OK"
}
How can I sort this json so I will only output everything inside routes?
Ajax:
function getDirections(lat, lng, destinationLat, destinationLng) {
$.ajax({
url: '/google',
type: 'post',
data: { lat: lat, lng: lng, destinationLat: destinationLat, destinationLng: destinationLng },
dataType: 'json',
success: function(data) {
console.log(data.routes);
},
error: function() { alert('boo!'); },
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Controller:
function getGoogle() {
$lat = Input::get('lat');
$lng = Input::get('lng');
$destinationLat = Input::get('destinationLat');
$destinationLng = Input::get('destinationLng');
$google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin='.$lat.','.$lng.'&destination='.$destinationLat.','.$destinationLng.'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
return response()->json(['data' => $google]);
}
//edit
console.log(data);
Object {data: "{↵ "geocoded_waypoints" : [↵ {↵ "ge…t_order" : []↵ }↵ ],↵ "status" : "OK"↵}↵"}data: "{↵ "geocoded_waypoints" : [↵ {↵ "geocoder_status" : "OK",↵ "place_id" : "ChIJuVnJ34G3e0gRW_oSYLOUxEc",↵ "types" : [ "premise" ]↵ },↵ {↵ "geocoder_status" : "OK",↵ "place_id" : "ChIJ0afvWH-3e0gRehrvBJAsflw",↵ "types" : [ "premise" ]↵ }↵ ],↵ "routes" : [↵ {↵ "bounds" : {↵ "northeast" : {↵ "lat" : 53.541228,↵ "lng" : -2.1114828↵ },↵ "southwest" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ }↵ },↵ "copyrights" : "Map data ©2017 Google",↵ "legs" : [↵ {↵ "distance" : {↵ "text" : "0.1 km",↵ "value" : 114↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 27↵ },↵ "end_address" : "Broseley House, 81 Union St, Oldham OL1 1PF, UK",↵ "end_location" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ },↵ "start_address" : "Ashton Arms, Oldham, UK",↵ "start_location" : {↵ "lat" : 53.5411291,↵ "lng" : -2.1114828↵ },↵ "steps" : [↵ {↵ "distance" : {↵ "text" : "41 m",↵ "value" : 41↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 7↵ },↵ "end_location" : {↵ "lat" : 53.54116,↵ "lng" : -2.1119794↵ },↵ "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eClegg St\u003c/b\u003e toward \u003cb\u003eAscroft St\u003c/b\u003e",↵ "polyline" : {↵ "points" : "agxeIvk{KIDEDADAF?H#JJr#"↵ },↵ "start_location" : {↵ "lat" : 53.5411291,↵ "lng" : -2.1114828↵ },↵ "travel_mode" : "DRIVING"↵ },↵ {↵ "distance" : {↵ "text" : "52 m",↵ "value" : 52↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 11↵ },↵ "end_location" : {↵ "lat" : 53.5407078,↵ "lng" : -2.1117626↵ },↵ "html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eHarrison St\u003c/b\u003e",↵ "maneuver" : "turn-left",↵ "polyline" : {↵ "points" : "ggxeIzn{KxAk#"↵ },↵ "start_location" : {↵ "lat" : 53.54116,↵ "lng" : -2.1119794↵ },↵ "travel_mode" : "DRIVING"↵ },↵ {↵ "distance" : {↵ "text" : "21 m",↵ "value" : 21↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 9↵ },↵ "end_location" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ },↵ "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003ePrinter St\u003c/b\u003e",↵ "maneuver" : "turn-right",↵ "polyline" : {↵ "points" : "mdxeInm{KJ|#"↵ },↵ "start_location" : {↵ "lat" : 53.5407078,↵ "lng" : -2.1117626↵ },↵ "travel_mode" : "DRIVING"↵ }↵ ],↵ "traffic_speed_entry" : [],↵ "via_waypoint" : []↵ }↵ ],↵ "overview_polyline" : {↵ "points" : "agxeIvk{KOJCL#TJr#xAk#J|#"↵ },↵ "summary" : "Ascroft St and Harrison St",↵ "warnings" : [],↵ "waypoint_order" : []↵ }↵ ],↵ "status" : "OK"↵}↵"__proto__: Objectconstructor: function Object()hasOwnProperty: function hasOwnProperty()isPrototypeOf: function isPrototypeOf()propertyIsEnumerable: function propertyIsEnumerable()toLocaleString: function toLocaleString()toString: function toString()valueOf: function valueOf()__defineGetter__: function __defineGetter__()__defineSetter__: function __defineSetter__()__lookupGetter__: function __lookupGetter__()__lookupSetter__: function __lookupSetter__()get __proto__: function __proto__()set __proto__: function __proto__()
Please check below thing it may help you. In JSON response you are passing data key with response so on ajax part you have to use data.data.routes to get proper output.
function getGoogle() {
$lat = Input::get('lat');
$lng = Input::get('lng');
$destinationLat = Input::get('destinationLat');
$destinationLng = Input::get('destinationLng');
$google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin=' . $lat . ',' . $lng . '&destination=' . $destinationLat . ',' . $destinationLng . '&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
return response()->json(['data' => json_decode($google)]);
// Google's response by default is in JSON, so I've converted to array `json_decode($google)`.
}
//Here is the json response you get from ajax success.
var json = {
"geocoded_waypoints": [
{
"geocoder_status": "OK",
"place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
"types": [
"premise"
]
},
{
"geocoder_status": "OK",
"place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
"types": [
"premise"
]
}
],
"routes": [
{
"bounds": {
"northeast": {
"lat": 53.541228,
"lng": -2.1114936
},
"southwest": {
"lat": 53.5406464,
"lng": -2.1120657
}
},
"copyrights": "Dane do Mapy ©2017 Google",
"legs": [
{
"distance": {
"text": "0,1 km",
"value": 112
},
"duration": {
"text": "1 min",
"value": 27
},
"end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"start_address": "Ashton Arms, Oldham, Wielka Brytania",
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"steps": [
{
"distance": {
"text": "39 m",
"value": 39
},
"duration": {
"text": "1 min",
"value": 7
},
"end_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
"polyline": {
"points": "egxeIxk{KEBEDADAF?H#JJr#"
},
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "52 m",
"value": 52
},
"duration": {
"text": "1 min",
"value": 11
},
"end_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
"maneuver": "turn-left",
"polyline": {
"points": "ggxeIzn{KxAk#"
},
"start_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "21 m",
"value": 21
},
"duration": {
"text": "1 min",
"value": 9
},
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
"maneuver": "turn-right",
"polyline": {
"points": "mdxeInm{KJ|#"
},
"start_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"travel_mode": "DRIVING"
}
],
"traffic_speed_entry": [],
"via_waypoint": []
}
],
"overview_polyline": {
"points": "egxeIxk{KKHCL#TJr#xAk#J|#"
},
"summary": "Ascroft St i Harrison St",
"warnings": [],
"waypoint_order": []
}
],
"status": "OK"
};
for(var jsonvalue in json.routes){
var legs = json.routes[jsonvalue].legs;
if(legs.length){
for(var legvalue in legs){
$("ul").append("<li>Distance : " + legs[legvalue].distance.text + " -- Duration : " +legs[legvalue].duration.text + " </li>")
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
</ul>
Assuming you have an Object {} (and not just a string of text) you should be able to do
console.log(Object.routes)
I think in success promise you aren't getting proper data format how you are expecting put a debug point on console.log in success promise and check the structure of the object and select the routes.
`success: function(data) {
console.log(data.routes);
}`
You can get a formatted stripped-down output with:
var formatted = JSON.stringify(data,
function(key, value) {
// remove geocoded_waypoints
if (key == "geocoded_waypoints") return;
// remove other branches...
return value;},
2);
... or just only return the few keys you need.
Source: W3C
just parse your response:
var res=JSON.parse(response);

Count in Firebase JavaScript

I have a sample JSON object below:
{
"product" : [ {
"description" : "This ball has air it.",
"id" : "product0",
"name" : "football",
"price" : 10
}, {
"description" : "Can kick upto long distance.",
"id" : "product1",
"name" : "soccer boots",
"price" : 5
}, {
"description" : "Long socks",
"id" : "product2",
"name" : "stockings",
"price" : 2
}, {
"description" : "This ball has air it.",
"id" : "product3",
"name" : "gloves",
"price" : 3
}, {
"description" : "Wear it pls.",
"id" : "product4",
"name" : "jersey",
"price" : 12
} ]
}
What can be the shortest way to find the number (count) of products in JavaScript? Does Firebase provide any query in JavaScript to find the count in an object?
Here is a simple solution. Just get the length of required array from the JSON Object.
var json = {
"product": [{
"description": "This ball has air it.",
"id": "product0",
"name": "football",
"price": 10
}, {
"description": "Can kick upto long distance.",
"id": "product1",
"name": "soccer boots",
"price": 5
}, {
"description": "Long socks",
"id": "product2",
"name": "stockings",
"price": 2
}, {
"description": "This ball has air it.",
"id": "product3",
"name": "gloves",
"price": 3
}, {
"description": "Wear it pls.",
"id": "product4",
"name": "jersey",
"price": 12
}]
};
console.log(json.product.length);
Incase of JSON string: Get the length like this
var json = '{ "product" : [ {"description" : "This ball has air it.","id" : "product0","name" : "football","price" : 10 }, {"description" : "Can kick upto long distance.","id" : "product1","name" : "soccer boots","price" : 5 }, {"description" : "Long socks","id" : "product2","name" : "stockings","price" : 2 }, {"description" : "This ball has air it.","id" : "product3","name" : "gloves","price" : 3 }, {"description" : "Wear it pls.","id" : "product4","name" : "jersey","price" : 12 } ]}';
var t = JSON.parse(json);
console.log(t.product.length);
You can save the object on JavaScript variable
var myData = {
"product" : [ {
"description" : "This ball has air it.",
"id" : "product0",
"name" : "football",
"price" : 10
}, {
"description" : "Can kick upto long distance.",
"id" : "product1",
"name" : "soccer boots",
"price" : 5
}, {
"description" : "Long socks",
"id" : "product2",
"name" : "stockings",
"price" : 2
}, {
"description" : "This ball has air it.",
"id" : "product3",
"name" : "gloves",
"price" : 3
}, {
"description" : "Wear it pls.",
"id" : "product4",
"name" : "jersey",
"price" : 12
} ]
}
Now you can get length
console.log(myData.product.length);

How get Data from a JSON Object Using JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
{
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
}
This is the server side response to my app and I want to get the user name and password values only.
Use JSON.parse() to parse the JSON response into a Javascript object. Then you can access the properties.
var obj = JSON.parse(response);
The username and password are in an array that's in the entities property, so you can access them as:
var username = obj.entities[0].username;
var password = obj.entities[0].password;
Get the data in a variable, say in variable data.
var data = {
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
};
//logging username and password fields
console.log(data.entities[0].username, data.entities[0].password);
JSON behaves like key value pair kind of collection. Assign this Json to Javascript variable and then you can get the values of JSON with respective key like
var myJson =
{
"action" : "get", "application" : "2c5ca3b0-be74-11e4-8ff3-
f7af49a474ef", "params" : { "ql" : [ "select * where
username='pqr'" ] }, "path" : "/logs", "uri" :
"https://api.usergrid.com/serv-d/demo1/logs", "entities" : [
{ "uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e", "type" :
"log", "created" : 1425036869840, "modified" :
1425036869840, "metadata" :
{ "path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
}, "pas sword" : "pqr", "username" : "pqr"
}], "timestamp" : 1425359738746, "duration" : 15,
"organization" : "serv-d", "applicationName" : "demo1",
"count" : 1 };
var action = myJSON.action;
var uri = myJSON.uri; and so on..
Assuming you store it as "obj", then you can do obj.entities[0].username (and likewise for password.
Assuming you are referring it as data, You can use data.entities[0].username to access username.
var data = {
"action": "get",
"application": "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params": {
"ql": [
"select * where username='pqr'"
]
},
"path": "/logs",
"uri": "https://api.usergrid.com/serv-d/demo1/logs",
"entities": [
{
"uuid": "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type": "log",
"created": 1425036869840,
"modified": 1425036869840,
"metadata": {
"path": "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password": "pqr",
"username": "pqr"
}
],
"timestamp": 1425359738746,
"duration": 15,
"organization": "serv-d",
"applicationName": "demo1",
"count": 1
};
alert(data.entities[0].username)
alert(data.entities[0].password)
var yourData = {
"action" : "get",
"application" : "2c5ca3b0-be74-11e4-8ff3-f7af49a474ef",
"params" : {
"ql" : [ "select * where username='pqr'" ]
},
"path" : "/logs",
"uri" : "https://api.usergrid.com/serv-d/demo1/logs",
"entities" : [ {
"uuid" : "97b0fd0a-be74-11e4-9324-b3bd8af7859e",
"type" : "log",
"created" : 1425036869840,
"modified" : 1425036869840,
"metadata" : {
"path" : "/logs/97b0fd0a-be74-11e4-9324-b3bd8af7859e"
},
"password" : "pqr",
"username" : "pqr"
}],
"timestamp" : 1425359738746,
"duration" : 15,
"organization" : "serv-d",
"applicationName" : "demo1",
"count" : 1
}
Because username and password is data of entities- that is an array of one element member
you may access the username data
var username = yourData.entities[0].username
Similarly for password

How to use if statement inside JSON?

How to use if statement inside JSON Here is the code:
.......................................................................................
var config =
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
},
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
This is the required result something like this:
var config =
[
if(page==true) {
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
} else {
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
Actually this way is wrong and makes a JavaScript syntax error.
Validating the JSON Schema Draft-07, JSON now supports the if...then...else keywords for conditional data representation.
Here is a quick example:
{
"type": "integer",
"minimum": 1,
"maximum": 1000,
"if": { "minimum": 100 },
"then": { "multipleOf": 100 },
"else": {
"if": { "minimum": 10 },
"then": { "multipleOf": 10 }
}
}
Edits
Using the OP's example in the context, it can be written like this:
{
"if": {
"page": true
},
"then": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
},
{
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"else": [
{
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
]
}
That's regular JavaScript, not JSON. Move the if statement outside:
if (page) {
var config = [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
}, {
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
];
} else {
var config = [
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
}
you can add an if inside JSON.
const config = [
...(page ? [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}] : [{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}]),
];
or perhaps this:
var config =
(page == true) ?
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
:
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
You can do it this way also (not saying this is the best way but it's another way and could be useful in some scenarios)
let config = [];
if (page) {
config.push({
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
});
config.push({
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
});
} else {
config.push({
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
});
}
You can use a library jsoncode that allows you to apply logical expressions directly into JSON and get the necessary result according to the transmitted model:
import jsoncode from './jsoncode.lib.mjs';
const json_src = {
"configs [AS ARRAY]": {
"[...IF page]": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
}, {
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"[IF !page]": {
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
}
};
const configsA = jsoncode(json_src, { page: true }).configs;
const configsB = jsoncode(json_src, { page: false }).configs;
console.log('configsA:', configsA);
console.log('configsB:', configsB);
https://www.npmjs.com/package/jsoncode

Categories