Setting 3rd Level Nested Attribute on a Backbone Model - javascript

I'm having trouble changing the location $id on this Backbone model.
{
"approved": null,
"caption": "This is my photo!",
"created": 1393537913,
"location": {
"_id": {
"$id": 5
},
"address1": "155 West Street",
"city": "Bangkok",
"country": "THA",
"latitude": "13.136",
"longitude": "100.2068",
"postalCode": "10330",
"region": "AP"
}
}
I've tried:
model.set({"location":{"_id":{"$id": 6}}})
But that obviously overwrites the entire location object.
model.set({"location._id":{"$id":6}})
Creates a new attribute on the model, "location._id".
So, how can I dig in to the location to change that attribute?

You can do like this :
var location = model.get('location');
location._id = { "$id": 6 };

Related

How to loop through JSON object that is array of objects?

I just need to retrieve an object by its id from this JSON object (peopleData). When I do typeof peopleData, it returns object. When I try to do typeof peopleData[0] (treating this object as an array because it has brackets as the opening and closing elements) it returns undefined. How do I loop through all of the objects to find the appropriate object if this JSON object is an array that returns "undefined" when I try to get a specific element of that array? I don't know how to enumerate over or de-structure this object since it is an array.
Here are the first few lines from the JSON that I was given (I changed the values but that is irrelevant. I am mainly emphasizing the bracket at the beginning). This is the raw JSON object that I copied from its raw form on GitHub:
[{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef"
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}, {
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
I have done this before with this exact data and it worked when I just used a small function that cycles through each element of the array, but I have no idea why it is not working now.
I diagnosed my problem incorrectly. It did not have to do with the JSON data. I forgot to use await when getting the data with Axios. Thanks so much for any effort you put in to help me with this.
You can use filter by the id you want.
const data = [{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
},
{
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}]
let result = data.filter(obj => obj.id === "237856238235")
//console.log(result)
console.log(result[0])

how to GET and store specific values as a list from JSON data(URL) in javascript?

I tried several approches and none of them works. I think this is because I am using JSON returned by django DRF.
I want to create a list of IFSC using this JSON in Jquery in my HTML template itself.
This is how my api returns JSON for any queryset.
{
"count": 134,
"next": "http://127.0.0.1:8000/api/bankdetailapi/?limit=5&offset=5&q=ABHY",
"previous": null,
"results": [
{
"ifsc": "ABHY0065001",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "RTGS-HO",
"address": "ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065002",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "ABHYUDAYA NAGAR",
"address": "ABHYUDAYA EDUCATION SOCIETY, OPP. BLDG. NO. 18, ABHYUDAYA NAGAR, KALACHOWKY, MUMBAI - 400033",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065003",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "BAIL BAZAR",
"address": "KMSPM'S SCHOOL, WADIA ESTATE, BAIL BAZAR-KURLA(W), MUMBAI-400070",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
}
]
}
The code I tried:
$(document).ready(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = `IFSC: ${data.ifsc}`
})
)}
It throws error in browser console that Uncaught ReferenceError: text is not defined . I want to use this IFSC list as autocomplete suggestions.
$("#q").keyup(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = ['']
for (var i=0;i<data.results.length;++i){text.push(data.results[i].ifsc)}
// var text = `IFSC: ${data.results.ifsc}`
console.log(text)
By using push method and iterating on whole data i managed to get list of all IFSC values.

how to print ipdata language name using javascript?

Hi guys I need to know how to print the language name in ipdata
I have this code at the bottom working well and the results appear correct but when I get the name of the language the results show the language name = undefined;
results
184.23.215.250
United States
<img src="https://ipdata.co/flags/us.png">
US
North America
Sonic Telecom LLC
undefined
my js vars is
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages.name;
you can try it from http://tiger222.atwebpages.com/set.php
You will find the data correct but, how do I get the language name correctly ?
var lang = response.languages->name; this is not working
var lang = response.languages.name; and this is not working
In the source data, languages is an array, e.g.
"languages": [
{
"name": "English",
"native": "English"
}
],
Therefore it can potentially contain multiple entries.
Assuming you just want the first language in the list, then you can address the first index of the array directly, like this:
var lang = response.languages[0].name;
P.S. -> is not valid syntax in JavaScript. You were perhaps thinking of PHP syntax there.
This is array
var lang = response.languages[0].name;
Languages is an array so you would have to map on its elements and get name out of it.
"languages": [
{
"name": "English",
"native": "English"
}
],
It may break if there are no languages in the array so you can do defensive code like below:
var lang = (response.languages && response.languages.length && response.languages[0].name) || '';
const response = {
"ip": "12.00.00.01",
"is_eu": false,
"city": "Any City",
"region": "Pennsylvania",
"region_code": "PA",
"country_name": "United States",
"country_code": "US",
"continent_name": "North America",
"continent_code": "NA",
"latitude": 49.9776,
"longitude": -95.3099,
"asn": "AS7018",
"organisation": "AT&T Services, Inc.",
"postal": "18083",
"calling_code": "1",
"flag": "https://ipdata.co/flags/us.png",
"emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
"emoji_unicode": "U+1F1FA U+1F1F8",
"carrier": {
"name": "AT&T",
"mcc": "310",
"mnc": "016"
},
"languages": [
{
"name": "English",
"native": "English"
}
],
"currency": {
"name": "US Dollar",
"code": "USD",
"symbol": "$",
"native": "$",
"plural": "US dollars"
},
"time_zone": {
"name": "America/New_York",
"abbr": "EDT",
"offset": "-0400",
"is_dst": true,
"current_time": "2019-05-30T08:52:43.569643-04:00"
},
"threat": {
"is_tor": false,
"is_proxy": false,
"is_anonymous": false,
"is_known_attacker": false,
"is_known_abuser": false,
"is_threat": false,
"is_bogon": false
},
"count": "1501"
};
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages[0].name;
console.log(lang);

AngularJs extracting values from JSON Object and attaching to $scope

I am receiving the following JSON data object
{
"ip": "**Removed**",
"country_code": "GB",
"country_name": "United Kingdom",
"region_code": "ENG",
"region_name": "England",
"city": "Plymouth",
"zip_code": "PL6",
"time_zone": "Europe/London",
"latitude": 50.442,
"longitude": -4.0828,
"metro_code": 0
}
How do I extract the first two values and attach them to the $scope so that they can be shown in the template when received.?
Assuming that you're getting it via http request your call would be like this:
$http.get("./getData.php").success(function(data) {
$scope.data = {};
$scope.data["ip"] = data["ip"];
$scope.data["country_code"] = data["country_code"];
}
You can set this whole object to a property on the scope in your controller:
$scope.jsonObject = jsonObject;
Then in your template, just access it like:
<span>{{jsonObject.country_code}}</span>
If I understood correctly, first store that JSON into one varaible
Var jsonData = {
"ip": "Removed",
"country_code": "GB",
"country_name": "United Kingdom",
"region_code": "ENG",
"region_name": "England",
"city": "Plymouth",
"zip_code": "PL6",
"time_zone": "Europe/London",
"latitude": 50.442,
"longitude": -4.0828,
"metro_code": 0
}
$scope.firstTwoValues = jsonData.ip+jsonData.country_cody;
For dynamic names u can use smth like this:
someDataService.get()
.then(function(res) {
var keys = Object.keys(res.data).splice(1,2);
angular.forEach(keys, function(key){
$scope[key] = res.data[key];
});
return $q.when();
}

How to use JSON Stringify when fields are own object types?

EDIT: Something like this, but this is not working either, but there is the problem I think
var stringifyObj = JSON.stringify({
"addressAddressId":$('#address').val(){
"cityId:"$('#city').val(){
"postalCode":$('#postalCode').val()
}
}
});
*When I generate test client in Netbeans, JSON-structure (GET/JSON) is like that, but how can I code that with Javascipt and Strinfy-function? *
"addressAddressId": {
"addressId": 1,
"address": "Järnvägen 2",
"address2": null,
"district": null,
"postalCode": "20360",
"phone": null,
"coordinates": null,
"latitude": null,
"longitude": null,
"directions": null,
"description": null,
"addrZipCityCountry": null,
"lastUpdated": 1361754860000,
"cityId": {
"cityId": 1,
"city": "",
"lastUpdate": 1361754850000,
"countryCountryId": {
"countryId": 1,
"country": "Sweden",
"lastUpdate": 1361754837000
}
}
},
QUESTION
What is the correct syntax when using JSON.stringify in case of own
object type like City-object inside of Address-object?
Should I add every field to json if not using
#JsonIgnoreProperties({""})? I just need address, city and postal
code. address is type of Address with field String address in server
side, City is type of City includes String-field for city name etc.
I'm not sure what are you trying to do with your Javascript function above, but if your goal is to produce JSON with such structure using Javascript, maybe you can try this :
var stringifyObj = JSON.stringify({
"addressAddressId": {
"addressId": 1,
"address": "Järnvägen 2",
"address2": null,
"district": null,
"postalCode": "20360",
"phone": null,
"coordinates": null,
"latitude": null,
"longitude": null,
"directions": null,
"description": null,
"addrZipCityCountry": null,
"lastUpdated": 1361754860000,
"cityId": {
"cityId": 1,
"city": "",
"lastUpdate": 1361754850000,
"countryCountryId": {
"countryId": 1,
"country": "Sweden",
"lastUpdate": 1361754837000
}
}
}
});
Basically, all you need to do is wrap the JSON string as a parameter for the JSON.stringify.
Or, if you need to build the object incrementally, instead of providing all the properties at once like above, maybe you can try this :
var obj = {};
//add properties as needed
//simple properties
obj.addressId = 1;
obj.address = "Järnvägen 2";
obj.address2 = null;
//nested properties
obj.cityId = {};
obj.cityId.cityId = 1;
obj.cityId.countryCountryId = {};
obj.cityId.countryCountryId.countryId = 1;
After all the object properties are properly filled, pass it to the JSON.stringify like this :
var stringifyObj = JSON.stringify(obj);
Or, to produce the JSON described on your example, you can further wrap the obj like this :
var stringifyObj = JSON.stringify({ addressAddressId = obj });
I hope you get the idea :)
And you are missing a comma here, though I can't say that is your issue.
"postalCode": {
"postalCode": $('#postalCode').val()
} <--- need comma here
"addressAddressId": {

Categories