how to update javascript variable array from c# - javascript

am working with this array in javascript of marks to show all marks in the map as static work is perfect
var markers = [
{
"title": 'Aksa Beach',
"lat": '31.6227697895779',
"lng": '-4.998779296875',
"description": '/www.google.com">Read more</a>'
}];
but if i can add some marks from model in html view is my problem
#foreach (var item in Model) {
markers.push({
"title": item.name,
"lat": item.lat,
"lng": item.long,
"description": item.descript
});
}

Wrap the values with single or double quotes. Also since item is a C# variable, you need to use #. You also need to use <text> tag as you are mixing C# code and plain text (js code)
<script>
var markers = [];
#foreach (var item in Model) {
<text>
markers.push({ "title": "#item.name",
"lat": "#item.lat",
"lng": "#item.long",
"description":"#item.descript"
});
</text>
}
</script>

Related

Store certain values in JSON into parameters in React

brand new to Javascript.
I have figured out how to get data back from a Monday.com board, and it is returned as a JSON value like this:
{
"boards": [
{
"items": [
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Cape Town, South Africa"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Paris, France"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "New York, NY, USA"
}
]
}
]
}
]
}
There are 3 items here, but this amount can be anything.
I need to get the location text (e.g. "Cape Town, South Africa") and then I need to use this later in an API call to get the weather of this location.
I finally managed to display in the console the location, like this:
console.log(JSON.stringify(this.state.boardData.boards[0].items[0].column_values[0].text));
Obviously this then displays what I want, but only the value of the first item.
I need to do this dynamically to get all the locations, and I need to store this into variables, so that I can then make an API call to get the weather of each of the 3 (or more) locations.
I am totally lost and have been struggling for hours. Once I manage to do this, I still have no idea how I'll make the API call but one thing at a time :)
Another approach:
const rawData = {boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = [];
for (const board of rawData.boards) {
for (const item of board.items) {
for (const value of item.column_values) {
locations.push(value.text);
}
}
}
console.log(locations);
You can extract the text with some amount of nested .map. Map boards => map items => map column_values. You will get an array of arrays of arrays. And then you can apply .flat() to unwrap them all. (.flat(Infinity); also can be used)
const apiData={boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = apiData.boards
.map((board) => board.items.map((i) => i.column_values.map((cv) => cv.text)))
.flat(2);
console.log(locations);
So in javascript we have an array function map, using which we can iterate over array that can be used here. It would look something like this:
let arr = boards[0].items.map(element => element.column_values[0].text)
and this arr will contain the list of all the city names, which you can further use to send the data to api.
(Edit: considering column_values to be array with one element only and items can have multiple elements)

Javascript dynamically create image/icon (marker) from data

I want to display a map (Google maps initially) in a website (e.g. the position of some runners in an event/race), alongisde some markers with the initials of each runner. That is, depending on the data I get in JSON format:
data = [
{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
}
{
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
]
I would like to represent the current position of each runner in the map with a marker identified by its initials (Mark Zein --> M.Z.). For instance (forgive me for this representation):
-----
|M.Z| _______________________road
----- --|-- /
|P.C| _________v________|
--|-- /
___v__________/
I know I can create a google.maps.Marker with a custom icon, but I am finding hard to create these icons dinamically based on data I receive (and that might change over time).
Is there a way to dynamically create images/icons from data? Or can you think of another way of generating these icons?
I've been doing some research but so far I didn't find something, so any help will be much appreciated!
Edited:
I am currently mocking the way I get the data, but the idea is to get the data from a socket. So what I have in my code right now is:
var json_socket = {
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
};
And how I add the markers:
var live_user = {lat: json_socket["lat"], lng: json_socket["lng"]};
var marker = new google.maps.Marker({
position: live_user,
map: map,
icon: "icon.png"
});
You can iterate over the array of markers with simple loop
I used the label to display the initials
var data = [{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
} {
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
];
for (var i = 0; i < data.length; i++) {
var item = data[i];
var latLng = new google.maps.LatLng(item.lat, item.lng);
var initials = item.full_name.match(/\b(\w)/g).join('');
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
label: initials,
icon: "icon.png"
});
}

create DOM elements with data value from a javascript

I have a site where some basic information is outpout in a javscript. I don't have access to the server side of things - and I wonder if I could use jQuery/Vanilla JS to create a DOM element with the value from that script?
The script looks like this:
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "Denmark",
"phone": "0000",
"nbrOrders": 0,
"name": "John doe",
"salesPerson": "Frederik Jensen",
"customerNo": "5464564564",
"email": "Johndoe#test.dk"
},
"order": {
"shippingSum": 0.0,
"orderno": "",
"voucher": "",
"currency": "",
"orderVat": 0.0,
"orderSum": 0.0,
"items": []
}
}
Small Example:
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"Denmark","phone":"0000","nbrOrders":0,"name":"John doe","salesPerson":"Frederik Jensen","customerNo":"5464564564","email":"Johndoe#test.dk"},"order":{"shippingSum":0.0,"orderno":"","voucher":"","currency":"","orderVat":0.0,"orderSum":0.0,"items":[]}}
var mainDiv = document.createElement("DIV");
var text1 = document.createTextNode("User Details");
var countryDiv = document.createElement("DIV");
var text2 = document.createTextNode("Country:");
var text3 = document.createTextNode(retailerData.user.country);
countryDiv.appendChild(text2)
countryDiv.appendChild(text3)
mainDiv.appendChild(text1);
mainDiv.appendChild(countryDiv);
document.body.appendChild(mainDiv);
Creating DOM-elements is pretty straight forward, it is just very explicit and will take some getting used to.
In its most basic use you need three methods:
createElement: creates an element (e.g. <div>)
createTextNode: creates text content for use in elements
appendChild: add a DOM-Node (such as an element or text) to another node
Creating new elements is always a document operation (oversimplification: the document is the HTML-tree of a webpage). So you always use document.create*, while the actual appending of those elements is done through the elements that should contain those newly created elements.
Now that I've mentioned these native DOM methods, lets put them to use and create an unordered list containing all user information.
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "Denmark",
"phone": "0000",
"nbrOrders": 0,
"name": "John doe",
"salesPerson": "Frederik Jensen",
"customerNo": "5464564564",
"email": "Johndoe#test.dk"
},
"order": {
"shippingSum": 0.0,
"orderno": "",
"voucher": "",
"currency": "",
"orderVat": 0.0,
"orderSum": 0.0,
"items": []
}
}
// create an <ul> element and add it to the <body>
var ul = document.body.appendChild(document.createElement('ul')),
key, li;
for (key in retailerData.user) {
// create a <li> element and add it to the <ul>
li = ul.appendChild(document.createElement('li'));
// create a <span>, which is added to the <li> and immediately put text
// into it (appendChild returns the appended child), this practice is
// known as 'chaining'
li.appendChild(document.createElement('span'))
.appendChild(document.createTextNode(key));
// now add the value to the <li>, it will end up after the <span> we
// created above
li.appendChild(document.createTextNode(retailerData.user[key]));
}
li span {
display: inline-block;
width: 8em;
font-style: italic;
}
var ul = document.body.appendChild(document.createElement('ul')),
key, li;
for (key in retailerData.user) {
li = ul.appendChild(document.createElement('li'));
li.appendChild(document.createElement('span'))
.appendChild(document.createTextNode(key));
li.appendChild(document.createTextNode(retailerData.user[key]));
}
The above snippet as working fiddle
In jQuery, the syntax is more convenient (this is one of the reasons it has become so popular)
var $ul = $('body').append('<ul>');
$.each(retailerData.user, function(key, value) {
$ul.append('<li><span>' + key + '</span>' + value + '</li>');
});
A working fiddle demonstrating jQuery.

Remove element from javascript object in angular repeat loop

I have data in the following form:
$scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1},
"5": {"cost": 802.85, "description": "test", "qty": 1}};
I'd like to loop through this data and display it alongside remove button. How can I make the button remove the row from the scope and also trigger angular digest? All of the tutorials seem to have the data in array, and splicing that array, this does not fit my needs.
This is what I have so far: http://jsfiddle.net/wbebc4cd/1/
As #dfsq mentioned, you have a typo in your function.
But more fundamentally, when repeating over the map, you should also remember the key. (See also How to use ng-repeat to iterate over map entries in AngularJS)
<tr ng:repeat="(key,item) in cart">
Then you can use the key to remove the item.
<td>[<a href ng:click="removeItem(key)">X</a>]</td>
http://jsfiddle.net/wbebc4cd/5/
here is the correct code for getting the item removed.
function CartForm($scope) {
$scope.cart=[{"id": 1, "cost": 802.85, "description": "test", "qty": 1}, {"id": 2, "cost": 802.85, "description": "test", "qty": 1}];
$scope.removeItem = function(item) {
var index = $scope.cart.indexOf(item);
$scope.cart.splice(index, 1);
}
}
You could try something like:
$scope.removeItem = function(item) {
var newCart = {};
angular.forEach($scope.cart, function(value, key){
if(value != item)
newCart[key] = value;
});
$scope.cart = newCart;
};
JSFiddle: http://jsfiddle.net/0v40rhfb/2/

Replacing all instances of a value in JSON using pure JavaScript

Is it possible using JavaScript only to replace all instances of the version with another number and then return the JSON structure intact?
{
"savedSearches": [{
"id": 123,
"version": 10,
"name": "Project Manager",
"query": "www.foo.com"
}, {
"id": 123,
"version": 10,
"name": "Project Manager",
"query": "www.foo.com"
}],
"deletedSavedSearches": []
}
I need this to be very quick and lightweight as I'll be using it within JMeter.
JSON structure is nothing more than a JavaScript object. You can iterate over its properties and modify their values as usual. For instance, to increase each version by one:
var json = { … }
for (var i in json.savedSearches) json.savedSearches[i].version += 1;
You can try this
var jsonObject = JSON.parse(yourJSONString);
for(var i = 0, len = jsonObject.savedSearches.length; i < len; i++) {
jsonObject.savedSearches[i].version = "Number you want here";
}
If you, for some reason, want to return a string:
JSON.stringify(jsonObject)
If you already have the object, you can skip the JSON.parse

Categories