push multidimensional array into json object - javascript

I am trying to insert some data in my mongodb database and I require data in some specific format
var location1 = [2,3];
var location2 = [];
location2.push(location1);
location2.push(location1);
var location3 = [];
location3.push(location2);
console.log(location3); //this is the format that i require for insert in mongodb
var couponData = {
location:{"type":"Polygon","coordinates":location3},
UsersTargetted:[],
};
console.log(couponData);
But while running the code i get output as:
{ location: { type: 'Polygon', coordinates: [ [Object] ] },
UsersTargetted: [] }
So, how to make coordinates value as given below:
[ [ [ 2, 3 ], [ 2, 3 ] ] ]
Thanks
Update:
I am not inserting anything in mongodb but creating a json object so that I can insert that object in the mongodb. My requirement is that coordinates field in json object should have value shown above. However, when I insert location3 variable, my console doesn`t show the location3 value, instead it is showing [[object]].
Update2:
Thanks Anand. data is getting stored in mongodb as expected. So no issue, maybe some problem in nodeeclipse.

If you are really worried about it then:
console.log( JSON.stringify( location3 );
And that should clear it up, showing the correct nested format.
Oddly, the syntax is documented as the way to do it here

Related

Having Issues with handling Python dictionaries in Javascript flask templates

So I am building a web application using flask that can track mutiple vehicles and provide updates. The python script helps gather all the data and puts them in a dictionary.
I am sending this dictionary over to the index.html with the javascript code within the HTML that initializes a map and places markers based on the coordinates received from python.
The issue I am having is this dictionary is not being parsed properly in js and as a result I get no data.
Right now I have the {{truck_dict}} placeholder to hold the dict object from python in the html.
PS. I am not the best at JS so dont judge XD
#Python Code
return render_template('pages/index.html', trucks = truck.driver_locator(truck.locations()))
#Even when I jsonify/json.dump the variable in the trucks object, nothing happens
#JS Code
var truck_dict = {{trucks | tojson}}
var i;
for (var key in truck_dict){
var value = truck_dict[key];
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: value
},
properties: {
title: 'Mapbox',
description: '1303'
}
}]
};
SAMPLE OUTPUT of the python generated dict
{'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]}
Here is the output:
var truck_dict = {'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]};
for (var i in truck_dict) {
console.log(i, truck_dict[i]);
}
output:
1301 [43.1220307, -78.9352247]
1302 [42.3107737, -77.2519131]
1303 [39.6435448, -75.9325289]
1304 [40.3809016, -74.5665863]
1305 [40.2453049, -74.5707928]
So, you need to log truck_dict, like:
var truck_dict = {{trucks | tojson}};
console.log(trucks);
console.log(truck_dict);
You're trying to index a dictionary.Using truck_dict[I] doesn't work here because your indices are not numbers (not possible in js anyway).
You need to access dictionary elements with their keys (ex. truck_dict['1301'] or truck_dict.1301) NOT indexes. If you want to iterate over each key (which you can use to reference the value mapped to that key), use:
for(var key in truck_dict) {
var value = truck_dict[key];
// do what you need with value and key here
}

Select Random Item (shown in pairs) from Array & Remove It, Restart Once Array is Empty

I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.

Get first item in a json list with Nodejs

I have a json data with this structure in Nodejs
{
ids:
[
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
}
How can I get the first value for "Deploy" key? Preferably JS code not extra libraries.
So for example, I want to get this value 1426ba8e-5d9d-4572-888d-2265ae7474ce which is the first entry.
var firstDeployValue = data.ids[0].split(':')[1]; should give you 1426ba8e-5d9d-4572-888d-2265ae7474ce If you want Deploy in there as well remove the split bit.
You can achieve that with split;
const data = {
ids: [
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
};
const result = data.ids[0].split(':')[1];
console.log(result);
you can just assign it to an object, like
jsonObj = {
ids:
[
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
}
and then just access it using jsonObj.ids[0].match(regexpattern)

How to read the values inside the json array

I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;

JSON - searching through keys with variable names (unknown)

Total JSON noob here. I'm trying to cycle through some JSON to pull out the first image from an array inside the object, and after 4 hours of having at it, I've decided I probably need some help.
I'm able to pull every value I need out of the object where I know the key, but I have some data that has non consistent key names that I need to basically iterate through looking for a partial match and then pulling the first on of these results.
The Json structure of the unknown element is structured like this:
"custom_fields": {
"content_0_subheading": [
"Title text"
],
"content_1_text": [
"Some text"
],
"content_2_image": [
[
"http://staging.livelivelyblog.assemblo.com/wp-content/uploads/2013/09/wellbeing-260x130.jpg",
260,
130,
true
]
],
"content_2_caption": [
""
]
}
What I'm after is the content_2_image in this case, but in another entry it could be content_20_image for all I know (there's a lot of data being pulled).
Any ideas of the best way to cycle through these unknown keys looking for a partial match on '_image' in the key or something, would be VERY appreciated.
Thanks!
You can't just search through every field with a partial match, so you'll have to iterate through every field and then check the field names for the match. Try something like this:
var json = {
"content_0_subheading": [
"Title text"
],
"content_1_text": [
"Some text"
],
"content_2_image": [
[
"http://staging.livelivelyblog.assemblo.com/wp-content/uploads/2013/09/wellbeing-260x130.jpg",
260,
130,
true
]
],
"content_2_caption": [
""
]
}
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (/content_[0-9]+_image/.test(key)) {
console.log('match!', json[key]); // do stuff here!
}
}
}
Basically, what we're doing is:
1) Loop through keys of json object for (var key in json)
2) Ensure the json has the property, and we're not accessing keys we don't want if (json.hasOwnProperty(key))
3) Check if key matches the regular expression /content_[0-9]+_image/
3a) Basically, test if it matches content_ANY NUMBERS_image where ANY NUMBERS is equal to at least one digit or more
4) Use that data however you please console.log(json[key])
Hope this helps!
You could use for ... in
for (key in object) {
// check match & do stuff
}
var json = JSON.parse(YOUR_JSON_STRING).custom_fields, //Fetch your JSON
image; //Pre-declare image
for(key in json){ //Search each key in your object
if(key.indexOf("image") != -1){ //If the index contains "image"
image = json[key]; //Then image is set to your image array
break; //Exit the loop
}
}
/*
image[0] //the URL
image[1] //the width
image[2] //the height
image[3] //your boolean

Categories