Retrieve a value from a script and replace a DIV with it - javascript

I am trying to retrieve from the code below the value of "city" which in this case is Bothell and use the text to replace a DIV in my HTML. This is the code:
$(document).ready(function() {
var f = function() {
realgeeks.analytics.send_activity({
"site_uuid": "09bce392-c259-4c5b-ba82-02547e30f980",
"property": {
"city": "**Bothell**",
"full_baths": 3,
"listing_status": "ACTIVE",
"year_built": 1984,
"zip": "98012",
"listing_days_on_market": 3,
"url": "http://www.bothellhomes.com/property/1265902/",
"sqft": "1306",
"tags": ["Snohomish", "Southeast Snohom",
"Thrashers Corner", "Parkshore", "Bothell",
"98012", "Parkshore Div 4", "1265902",
"Northshore"
],
"longitude": -122.204533,
"beds": 3,
"mls": "1265902",
"state": "WA",
"images": [
"https://property-media.realgeeks.com/40/8039f526bebf11225fda49555d1f4217.jpg",
"https://property-media.realgeeks.com/40/cd649b5ae431bec9fe4a5802a6520f5e.jpg",
"https://property-media.realgeeks.com/40/a43099b8b8b30772b019ac2aaea3460f.jpg"
],
"latitude": 47.830478,
"listing_price": "440000",
"type": "Single Family Residential",
"list_date": "2018-04-01T00:00:00+00:00",
"street_address": "18430 20th Dr SE"
},
"type": "property_viewed"
});
};
f();
$(document).on('fb-lead-login', f);
});
How would I go about doing this, knowing I don't have access to this block of code due to my web provider?

Related

What methods do I use to manipulate data of an array within an Object? (Pseudo Code only)

Backstory (skipable):
Hello, I'm a student at Lambda school. Recently we had a JS assessment test in order to progress to the next unit, but I wounded up flunking it twice. So now I have to repeat Unit 1. I'm here today in order to finally knock out that damn exam. I don't have a problem working with Arrays or Objects, what I do have a problem with is figuring out a way to solve issues when they are combined. It's like: "What the hell, do I use map or Object.Key?" Those types of problems appeared throughout the exam. It's fine to challenge students, but I never worked with both at the same time before. The approach was completely lost on me and before I knew it, my 3 hours were up two days straight.
What I hope you can provide:
I'm going to provide one problem and show you the work that I did. What I would like is for you to formulate pseudo code for me to work out that problem. I need to learn how to use Pseudo code if I want to be a good web engineer. Please do not solve the problem for me, all I ask is pseudo code. I'll try to work on the problem based on the pseudo code I feel is manageable for me to do. Thanks in Advance.
Problem and current Status:
/**
* ### Challenge `getSecondStarshipName`
* MVP Challenge 🤓
*
* #instructions
* Return second starship's name from `starships` property.
* If length is 0. Return 'none'
*/
function getSecondStarshipName(character) {
// TODO: Add your code here.
const checkProperty = character.hasOwnProperty("starships");
const checkArray = character.isArray("starships");
const secondShipLength = character.starships[1].length;
const secondShipName = character.starships[1].name;
if (checkProperty && checkArray) {
if (secondShipLength >= 2) {
return secondShipName;
} else {
return "none";
}
} else {
return "none";
}
}
Data
window.lukeSkywalker = require('./person-1.json')
window.leiaOrgana = require('./person-5.json')
window.obiWanKenobi = require('./person-10.json')
},{"./person-1.json":2,"./person-10.json":3,"./person-5.json":4}],2:[function(require,module,exports){
module.exports={
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"homeworld": "Tatooine",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"Revenge of the Sith",
"The Force Awakens"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Snowspeeder",
"model": "t-47 airspeeder",
"manufacturer": "Incom corporation",
"cost_in_credits": null,
"length": "4.5",
"max_atmosphering_speed": "650",
"crew": 2,
"passengers": 0,
"cargo_capacity": "10"
},
{
"name": "Imperial Speeder Bike",
"model": "74-Z speeder bike",
"manufacturer": "Aratech Repulsor Company",
"cost_in_credits": 8000,
"length": "3",
"max_atmosphering_speed": "360",
"crew": 1,
"passengers": 1,
"cargo_capacity": "4"
}
],
"starships": [
{
"name": "X-wing",
"model": "T-65 X-wing",
"manufacturer": "Incom Corporation",
"cost_in_credits": 149999,
"length": "12.5",
"max_atmosphering_speed": "1050",
"crew": 1,
"passengers": 0,
"cargo_capacity": "110",
"consumables": "1 week",
"hyperdrive_rating": "1.0",
"MGLT": "100",
"starship_class": "Starfighter"
},
{
"name": "Imperial shuttle",
"model": "Lambda-class T-4a shuttle",
"manufacturer": "Sienar Fleet Systems",
"cost_in_credits": 240000,
"length": "20",
"max_atmosphering_speed": "850",
"crew": 6,
"passengers": 20,
"cargo_capacity": "80000",
"consumables": "2 months",
"hyperdrive_rating": "1.0",
"MGLT": "50",
"starship_class": "Armed government transport"
}
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
},{}],3:[function(require,module,exports){
module.exports={
"name": "Obi-Wan Kenobi",
"height": "182",
"mass": "77",
"hair_color": "auburn, white",
"skin_color": "fair",
"eye_color": "blue-gray",
"birth_year": "57BBY",
"gender": "male",
"homeworld": "Stewjon",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"The Phantom Menace",
"Attack of the Clones",
"Revenge of the Sith"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Tribubble bongo",
"model": "Tribubble bongo",
"manufacturer": "Otoh Gunga Bongameken Cooperative",
"cost_in_credits": null,
"length": "15",
"max_atmosphering_speed": "85",
"crew": 1,
"passengers": 2,
"cargo_capacity": "1600"
}
],
"starships": [
{
"name": "Jedi starfighter",
"model": "Delta-7 Aethersprite-class interceptor",
"manufacturer": "Kuat Systems Engineering",
"cost_in_credits": 180000,
"length": "8",
"max_atmosphering_speed": "1150",
"crew": 1,
"passengers": 0,
"cargo_capacity": "60",
"consumables": "7 days"
},
{
"name": "Trade Federation cruiser",
"model": "Providence-class carrier/destroyer",
"manufacturer": "Rendili StarDrive, Free Dac Volunteers Engineering corps.",
"cost_in_credits": 125000000,
"length": "1088",
"max_atmosphering_speed": "1050",
"crew": 600,
"passengers": 48247,
"cargo_capacity": "50000000",
"consumables": "4 years"
},
{
"name": "Naboo star skiff",
"model": "J-type star skiff",
"manufacturer": "Theed Palace Space Vessel Engineering Corps/Nubia Star Drives, Incorporated",
"cost_in_credits": null,
"length": "29.2",
"max_atmosphering_speed": "1050",
"crew": 3,
"passengers": 3,
"cargo_capacity": null,
"consumables": null
},
{
"name": "Jedi Interceptor",
"model": "Eta-2 Actis-class light interceptor",
"manufacturer": "Kuat Systems Engineering",
"cost_in_credits": 320000,
"length": "5.47",
"max_atmosphering_speed": "1500",
"crew": 1,
"passengers": 0,
"cargo_capacity": "60",
"consumables": "2 days"
},
{
"name": "Belbullab-22 starfighter",
"model": "Belbullab-22 starfighter",
"manufacturer": "Feethan Ottraw Scalable Assemblies",
"cost_in_credits": 168000,
"length": "6.71",
"max_atmosphering_speed": "1100",
"crew": 1,
"passengers": 0,
"cargo_capacity": "140",
"consumables": "7 days"
}
],
"created": "2014-12-10T16:16:29.192000Z",
"edited": "2014-12-20T21:17:50.325000Z",
"url": "https://swapi.co/api/people/10/"
}
},{}],4:[function(require,module,exports){
module.exports={
"name": "Leia Organa",
"height": "150",
"mass": "49",
"hair_color": "brown",
"skin_color": "light",
"eye_color": "brown",
"birth_year": "19BBY",
"gender": "female",
"homeworld": "Alderaan",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"Revenge of the Sith",
"The Force Awakens"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Imperial Speeder Bike",
"model": "74-Z speeder bike",
"manufacturer": "Aratech Repulsor Company",
"cost_in_credits": 8000,
"length": "3",
"max_atmosphering_speed": "360",
"crew": 1,
"passengers": 1,
"cargo_capacity": "4"
}
],
"starships": [],
"created": "2014-12-10T15:20:09.791000Z",
"edited": "2014-12-20T21:17:50.315000Z",
"url": "https://swapi.co/api/people/5/"
}
},{}]},{},[1]);
How I would approach the problem (Pseudo Code):
//Create a variable called starship2nd
//Assign starship2nd the 2nd starship of each character.
//Check the length of the 2nd starship of each character. [[I'm stuck on this phase.]]
//Return 'none' after the checker function iterates through the Object's array. [[[Not sure how to do this part either..]]
Failed Solutions (Are they repairable? O_O)
solution 1 (failed)
const starship2nd = character.starships[1].name
const shipLength = starship2nd.length
function checkLength () {
if (shipLength === 0) {
return 'none'
}
return checkLength()
Thank you for your time. ^_^
Here is some pseudo code for you
if (character has property 'starships' and it is an array) {
if (length of starships is at least 2) {
return name property of second starship
} else {
return none
}
} else {
return none
}
You might think that some of those checks are overkill and not necessary since you know your input, but it is always good practice to double check properties and lengths before you begin accessing and assuming.
I hope that helps you with reasoning about the problem.

Change JSON format/layout

I have a universal variable on my website which includes line items with relevant details. These line items are reflective of what the user has in their cart. I am integrating with a third party who require the data passed through to them to be formatted slightly different. The below is the data layer currently on my website:
"lineItems": [
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo"
},
"quantity": 1
}
]
The below is what format the third party needs:
"lineItems": [
{
"sku": "s83y016b5",
"name": "Jeans",
"description": "A super great pair of jeans.",
"category": "Everyday Wear",
"other": {"fieldName": "This can be a string or any value you like"}
"unitPrice": 11.99,
"salePrice": 11.99,
"quantity": 2,
"totalPrice": 23.98
"imageUrl": "http://www.my-website.com/a/p/shirt.jpeg",
"productUrl": "http://www.my-website.com/index.php/shirt.html",
}]
Obviously this needs to be dynamic based on the products in the cart. What I intend to do is use javascript to amend the data and send this to the third party via Google Tag Manager.
Any help would be greatly appreciated. Any questions welcome.
This should be close to what you're looking for.
let oldLineItems = "your object";
let newLineItems = {};
newLineItems.lineItems = [];
for (let i in oldLineItems.lineItems) {
newLineItems.lineItems[i] = {};
for (let key in oldLineItems.lineItems[i].product)
{
newLineItems.lineItems[i][key] = oldLineItems.lineItems[i].product[key];
}
}
See code below.
I'm not sure how your lineItems object is set up, but below I just created an array called line Items. If line items is a key in an object which I suspect from your snippet above, you will have to go a level deeper in the for loops used in my example below.
Simply add further details to the new object in the nested for in loops below.
var lineItems =
[
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 1
},
{
"product": {
"id": "s83y01699",
"sku_code": "s83y01699",
"url": "/en-gb/pants/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/pants.jpeg",
"name": "Pants",
"manufacturer": "",
"category": "Casual Wear",
"stock": 90,
"currency": "au",
"unit_sale_price": 14,
"unit_price": 14,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 14
},
];
var newLineItems = [];
for(var char in lineItems){
// Adding some values to newLineItems.
newLineItems.push({
sku: lineItems[char].product.sku_code,
name: lineItems[char].product.name,
description: lineItems[char].product.description,
category: lineItems[char].product.category,
quantity: lineItems[char].quantity
});
}
console.log(JSON.stringify(newLineItems));

How to add post fields on the basis of result of elastic search

Actually i want to add "is_promoted" field in the response according to the result of elastic search if the "doc_count" is 1 then i have to fetch the id of the property and "is_promoted" flag from the actual result(Which you can see at the question).Its like a post filter in the elastic search. but i want add condition in the post filter. please see the current and expected output.
And below is the current output of the elastic query
{
"total_records": 32392,
"fetched_records": 3845,
"result": [
{
"key": "dp3w",
"doc_count": 343,
"centroid": {
"location": {
"lat": 41.919059987131064,
"lon": -87.71653202438385
},
"count": 343
}
},
{
"key": "djvw",
"doc_count": 1,
"centroid": {
"location": {
"lat": 33.49416188221888,
"lon": -82.0443208285174
},
"count": 1
}
},
{
"key": "9qhs",
"doc_count": 1,
"centroid": {
"location": {
"lat": 34.52696419113244,
"lon": -117.29711956000672
},
"count": 1
}
}
]
}
So i want to add field "is_promoted" if the "doc_count" is 1 and below is the expected output
{
"total_records": 32392,
"fetched_records": 3845,
"result": [
{
"key": "dp3w",
"doc_count": 343,
"centroid": {
"location": {
"lat": 41.919059987131064,
"lon": -87.71653202438385
},
"count": 343
}
},
{
"key": "djvw",
"doc_count": 1,
"is_promoted":true,
"centroid": {
"location": {
"lat": 33.49416188221888,
"lon": -82.0443208285174
},
"count": 1
}
},
{
"key": "9qhs",
"doc_count": 1,
"is_promoted":true,
"centroid": {
"location": {
"lat": 34.52696419113244,
"lon": -117.29711956000672
},
"count": 1
}
}
]
}
I used aggregation for that.
query.bool.minimum_should_match = 1;
aggQuery.zoomedin = {
filter: {
geo_bounding_box: {
location: {
top_left: {
lat: params.geo_bounding_box.location.nw.lat,
lon: params.geo_bounding_box.location.nw.lng
},
bottom_right: {
lat: params.geo_bounding_box.location.se.lat,
lon: params.geo_bounding_box.location.se.lng
}
}
}
},
aggregations: {
result: {
geohash_grid: {
field: "location",
precision: zoomLevel
},
"aggs": {
"centroid": {
"geo_centroid": { "field": "location" }
}
}
}
}
Below is the record structure in my elastic search. I hope it will help you to understand the senario
"hits": {
"total": 7967,
"max_score": 1,
"hits": [
{
"_index": "biproxi-test",
"_type": "listings",
"_id": "5126",
"_score": 1,
"_source": {
"address_line1": "Brandon Town Center Drive",
"address_line2": "USA",
"building_class": null,
"building_type": null,
"built_year": null,
"cap_rate": null,
"category": 1,
"city": "Brandon",
"country": "United States",
"county": "Hillsborough",
"floor_location": null,
"inplace_occupancy": null,
"land_size": 3,
"lease_type_id": null,
"lease_type": null,
"listing_group": "Retail",
"listing_type": [
1
],
"location": {
"lat": 27.937159,
"lon": -82.327498
},
"no_of_units": null,
"postal_code": "33511",
"price": 2185000,
"renovated_year": null,
"square_feet": null,
"state": "Florida",
"state_code": "FL",
"title": "3+- Acres at Brandon Town Center",
"status": 2,
"listing_image": "https://biproxi.s3.amazonaws.com/image/listing/5126/caf39154-fb42-483f-9320-9e9c394be66b.jpg",
"seller_id": "113157245308689129523",
"is_promoted": false
}
}, {
"_index": "biproxi-test",
"_type": "listings",
"_id": "5213",
"_score": 1,
"_source": {
"address_line1": "1909 N. Columbia Street",
"address_line2": "USA",
"building_class": null,
"building_type": null,
"built_year": "1996",
"cap_rate": null,
"category": 2,
"city": "Milledgeville",
"country": "United States",
"county": "Baldwin",
"floor_location": null,
"inplace_occupancy": null,
"land_size": null,
"lease_type_id": null,
"lease_type": null,
"listing_group": "Retail",
"listing_type": [
1
],
"location": {
"lat": 33.1086,
"lon": -83.25388
},
"no_of_units": null,
"postal_code": "31061",
"price": null,
"renovated_year": null,
"square_feet": null,
"state": "Georgia",
"state_code": "GA",
"title": "Milledge Village - 1 Space Remaining",
"status": 2,
"listing_image": "https://biproxi.s3.amazonaws.com/image/listing/5213/33d1cd5b-11a1-427d-8948-2e2db3d8e7f2.jpg",
"seller_id": "113157245308689129523",
"is_promoted": false
}
}
}]}
Okay, so, from the discussion in the direct comments under your OP I understand that you only want to add is_promoted field to some of the objects in the result array of the ES response, according to a certain condition.
What you need to do is very simple: loop through the result array, check the condition for each object and add the property.
for (const obj of elasticSearchResult.result) {
if (+obj.doc_count <= 1) {
obj['is_promoted'] = true;
}
}
I add the + sign in front of the obj.doc_count to ensure it's parsed to int and thus conducting a proper conditional comparison. The is_promoted property is added as an array key to ensure there are no compile or runtime errors of the sort of Property does not exist, since we create a new property in the object.
I don't know why do you use this aggregation functionality. You problem is purely JavaScript related and has nothing to do with ES or Node.js in particular.
P.S. This solution is based on the fact I understand your question correctly. Otherwise, please extend or improve your OP.

Display current number of Facebook group members using JavaScript

Is there a way to display the current number of members of my Facebook group on a SquareSpace code block (which only accepts HTML and JavaScript)?
Totally.
You can use Facebook Graph to accomplish what you want. Using an ordinary HTTPS request, I got this JSON-formatted results :
{
"id": "165227436975532",
"about": "Salon de Th\u00e9 style traditionnelle ..!!",
"can_post": false,
"category": "Restaurant/Cafe",
"category_list": [
{
"id": "203462172997785",
"name": "Tea Room"
}
],
"checkins": 66,
"cover": {
"cover_id": "476669145831358",
"offset_x": 0,
"offset_y": 54,
"source": "https://scontent.xx.fbcdn.net/hphotos-xpt1/v/t1.0-9/11536065_476669145831358_6075091507244297763_n.jpg?oh=7c6940ee3f2566884609fc59da224b67&oe=563A1B1D",
"id": "476669145831358"
},
"has_added_app": false,
"is_community_page": false,
"is_published": true,
"likes": 1246,
"link": "https://www.facebook.com/arabiccafe",
"location": {
"city": "Sousse",
"country": "Tunisia",
"latitude": 35.864546,
"longitude": 10.5988045,
"street": "Hammem Sousse",
"zip": "4011"
},
"name": "Arabica Cafe",
"parking": {
"lot": 0,
"street": 0,
"valet": 0
},
"phone": "21770198",
"talking_about_count": 6,
"username": "arabiccafe",
"were_here_count": 66
}
In order to get these info, you can use a normal XHR request (or jQuery.ajax if you use jQuery) and make a GET request to this URL :
https://graph.facebook.com/arabiccafe?access_token={your_token}
You can generate a token following these directives.

Retrieve Youtube Tags using Jquery

I'm trying to figure out how to retrieve Youtube Tags and use them in my code behind, but I can't even seem to retrieve any information whatsoever. What would be the best way to retrieve tags with a delimiter like a , or a ; ?
var video_id='VA770wpLX-Q';
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
alert(data.data.tags);
});
This is what the Json object looks like:
{
"apiVersion": "2.1",
"data": {
"id": "VA770wpLX-Q",
"uploaded": "2011-02-24T22:31:02.000Z",
"updated": "2012-04-08T21:37:06.000Z",
"uploader": "drdrevevo",
"category": "Music",
"title": "Dr. Dre - I Need A Doctor (Explicit) ft. Eminem, Skylar Grey",
"description": "Music video by Dr. Dre performing I Need A Doctor featuring Eminem and Skylar Grey (Explicit). © 2011 Aftermath Records",
"tags": ["Dr", "Dre", "Eminem", "New", "Song", "Skylar", "Grey", "GRAMMYs", "Dr.", "Need", "Doctor", "video", "Eazy", "N.W.A.", "NWA", "easy", "drdre", "and", "em"],
"thumbnail": {
"sqDefault": "http://i.ytimg.com/vi/VA770wpLX-Q/default.jpg",
"hqDefault": "http://i.ytimg.com/vi/VA770wpLX-Q/hqdefault.jpg"
},
"player": {
"default": "http://www.youtube.com/watch?v=VA770wpLX-Q&feature=youtube_gdata_player"
},
"content": {
"5": "http://www.youtube.com/v/VA770wpLX-Q?version=3&f=videos&app=youtube_gdata"
},
"duration": 457,
"aspectRatio": "widescreen",
"rating": 4.902695,
"likeCount": "430519",
"ratingCount": 441253,
"viewCount": 88270796,
"favoriteCount": 306556,
"commentCount": 270597,
"status": {
"value": "restricted",
"reason": "requesterRegion"
},
"restrictions": [{
"type": "country",
"relationship": "deny",
"countries": "DE"
}],
"accessControl": {
"comment": "allowed",
"commentVote": "allowed",
"videoRespond": "allowed",
"rate": "allowed",
"embed": "allowed",
"list": "allowed",
"autoPlay": "denied",
"syndicate": "allowed"
}
}
}
Youtube no longer supports "tag" functionality with it's API.

Categories

Resources