AngularJS multiple Scope needed for Autocomplete - angularjs

I have an array structure like this.
[
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
I need $scope like below for my autocomplete search.
$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];
can anyone help to get this using angularjs controller.
Thanks in Advance.!

Use MAP
$scope.users = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
];
$scope.cities = $scope.users.map(function(obj){
return obj.city;
});
console.log($scope.cities);

You can also create a helper function that would do that for you and you don't have to define a map per function that you want, and you do it in just one run (hence just a bit faster)
Sample here ;)
var myArray = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
function toScope(scopedPropertieNames, array) {
scopedPropertieNames.forEach(function(propertyName) {
if (! $scope[propertyName]) {
$scope[propertyName] = []
}
});
array.forEach(function (objecInArray) {
scopedPropertieNames.forEach(function(propertyName) {
$scope[propertyName].push(objecInArray[propertyName])
})
});
}
toScope(['name', 'city'], myArray);
console.log($scope) //{name: Array[3], city: Array[3]}

You can use MAP..
$scope.YourBigArray = [{
"id": "1",
"name": "John",
"city": "NY"
}, {
"id": "2",
"name": "Gerold",
"city": "LA"
}, {
"id": "3",
"name": "Stuart",
"city": "Boston"
}];
$scope.names = $scope.YourBigArray.map(function(object) {
return object.name;
});
$scope.cities = $scope.YourBigArray.map(function(object) {
return object.city;
});
You can do a filter to use unique things in array of names and cities..
function filterForDuplicate(things) {
return things.filter(function(item, pos) {
return things.indexOf(item) === pos;
});
}

Related

How to iterate object when it contains array of objects?

Input :
{
"id": "123",
"address": [{
"street": "5",
"city": "ameerpet",
"pin": "500073"
}, {
"street": "6",
"city": "sec",
"pin": "500020"
}]
}
Note: ["LAA001","LAA002","LAA003"] -> use this as a variable
Required output:
[{
"id": "123",
"lob": "LAA001",
"attributeText": "5"
},
{
"id": "123",
"lob": "LAA001",
"attributeText": "6"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "ameerpet"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "sec"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500073"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500020"
}
]
If you are using JavaScript, that should work:
var input = { "id": "123", "address": [ { "street": "5", "city": "ameerpet", "pin": "500073" }, { "street": "6", "city": "sec", "pin": "500020" }] }
var iob = ["LAA001","LAA002","LAA003"]
var output = []
input['address'].forEach((item, index) => {
var keyIndex = 0
for(const key in item){
let obj = {
"id": input['id'],
"lob": iob[keyIndex],
"attributeText": item[key]
}
output.push(obj)
keyIndex += 1
}
%dw 2.0
output application/json
var inp = ["LAA001","LAA002","LAA003"]
var inp1 = payload.address.street ++ payload.address.city ++ payload.address.pin
---
inp1 map {
id: payload.id,
lob: inp[(($$)/2)],
attributeText: $
}

how can i return fetch() in map() loop

I wrote a webapp about weather and i used weatherbit api that is just free part. i want to fetch() funk in map() loop .
i have an object which has cityname and country name . map() return every cityname and country with fetch()
how can i do that?
one more question every step of map() loop i get one JSON .. Maybe and of the loop i have 10 JSON... How can i match all Json into one Json?
here is the code..
const cityName = [
{
"id": 1,
"name": "Ingolstadt",
"country": "GE",
},
{
"id": 2,
"name": "Vienna",
"country": "AT",
},
{
"id": 3,
"name": "Istanbul",
"country": "TR",
},
{
"id": 4,
"name": "London",
"country": "GB",
},
{
"id": 5,
"name": "Ankara",
"country": "TR",
},
{
"id": 6,
"name": "Paris",
"country": "FR",
},
{
"id": 7,
"name": "Barcelona",
"country": "ES",
},
{
"id": 8,
"name": "Amsterdam",
"country": "NL",
},
{
"id": 9,
"name": "Belgrade",
"country": "RS",
},
{
"id": 10,
"name": "Munich",
"country": "GE",
}
]
//should return all city which are in object
const citySource = cityName.map((name , country) => {
// get api from weatherbit api , but i dont know ${name} and ${country} right sycntax
fetch(`https://api.weatherbit.io/v2.0/current?city=${name}&country=${country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
.then(response => response.json())
.then( users => console.log(users));
})
According to MDN:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Here you have working example:
const cityName = [
{
"id": 1,
"name": "Ingolstadt",
"country": "GE",
},
{
"id": 2,
"name": "Vienna",
"country": "AT",
},
{
"id": 3,
"name": "Istanbul",
"country": "TR",
},
{
"id": 4,
"name": "London",
"country": "GB",
},
{
"id": 5,
"name": "Ankara",
"country": "TR",
},
{
"id": 6,
"name": "Paris",
"country": "FR",
},
{
"id": 7,
"name": "Barcelona",
"country": "ES",
},
{
"id": 8,
"name": "Amsterdam",
"country": "NL",
},
{
"id": 9,
"name": "Belgrade",
"country": "RS",
},
{
"id": 10,
"name": "Munich",
"country": "GE",
}
]
//should return all city which are in object
const citySource = cityName.map((city) => {
fetch(`https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
.then(response => response.json())
.then( users => console.log(users));
})

to make able list item show their details on click

I am trying to get the latitude and longitude of the cities according to id...for example if i will click on kanpur it will show its latitude which is returning from API.But what i did is returning latitude of only last city which is returning from API.
my app.js code is:
.controller('AppCtrl', function($scope,
$http,$ionicModal,$cordovaGeolocation, $ionicLoading, $ionicPlatform) {
$scope.currentItem = 1;
$scope.latitude;
$scope.longitude;
$scope.ers = {
'agency_device_id' : ''
};
$scope.submit = function(){
var link = 'http://trendytoday.in/ers/api/DeviceAlarms';
$http.post(link, {ers: $scope.ers},{headers: {'Content-Type': 'application/json'} }).then(function (res){
// $scope.mssg = res.data.ers.resMessage;
// $scope.resp = res.data.ers.response;
$scope.arr = [];
angular.forEach(res.data.ers.data.alarms, function(value) {
$scope.arr.push(value);
//console.log(value.city)
latitude=value.lattitude;
longitude=value.longitude;
})
});
}
$scope.getdetails = function(){
window.alert(latitude);
};
});
and API response is:
{
"ers": {
"resMessage": "1",
"response": "Success",
"data": {
"alarms": [
{
"id": "1",
"alarm_id": "2",
"title": "Fire",
"description": "fire",
"type": "Fire",
"priority": "High",
"address": "Kanpur, Uttar Pradesh, India",
"city": "Kanpur",
"state": "UP",
"country": "India",
"zipcode": "123456",
"lattitude": "26.449923",
"longitude": "80.3318736"
},
{
"id": "3",
"alarm_id": "4",
"title": "test-02",
"description": "test-02",
"type": "Medical",
"priority": "High",
"address": "Borivali West, Mumbai, Maharashtra, India",
"city": "Mumbai",
"state": "MH",
"country": "India",
"zipcode": "123456",
"lattitude": "19.2461644",
"longitude": "72.85090560000003"
}
]
}
}
}
Assuming your $scope.currentItem is the id of the selected city such as kanpur, then when the API returns the data, check for this value to match the id and set the $scope variables.
I hope you get the idea.
function MyCtrl($scope) {
$scope.currentItem = 1;
$scope.latitude;
$scope.longitude;
$scope.submit = function() {
$scope.res = {
data: {
"ers": {
"resMessage": "1",
"response": "Success",
"data": {
"alarms": [{
"id": "1",
"alarm_id": "2",
"title": "Fire",
"description": "fire",
"type": "Fire",
"priority": "High",
"address": "Kanpur, Uttar Pradesh, India",
"city": "Kanpur",
"state": "UP",
"country": "India",
"zipcode": "123456",
"lattitude": "26.449923",
"longitude": "80.3318736"
},
{
"id": "3",
"alarm_id": "4",
"title": "test-02",
"description": "test-02",
"type": "Medical",
"priority": "High",
"address": "Borivali West, Mumbai, Maharashtra, India",
"city": "Mumbai",
"state": "MH",
"country": "India",
"zipcode": "123456",
"lattitude": "19.2461644",
"longitude": "72.85090560000003"
}
]
}
}
}
}
$scope.arr = [];
angular.forEach($scope.res.data.ers.data.alarms, function(value) {
$scope.arr.push(value);
if ($scope.currentItem == value.id) {
$scope.latitude = value.lattitude;
$scope.longitude = value.longitude;
}
});
}
$scope.submit();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app ng-controller="MyCtrl">
Long: {{longitude}}
Lati: {{latitude}}
</body>
the only thing i changed is i passed obj as a parameter to getdetails function.
$scope.getdetails = function(obj){
alert(obj.lattitude);
}
and in html:
<div ng-repeat="obj in arr " ng-click="getdetails(obj)">
<p><b>{{obj.city}}</b></p>
</div>

How to access a single object from a JSON array

Okay so I have a JSON:
{
"Concepts": [
{
"Concept": "1",
"Description": "siopao"
},
{
"Concept": "4",
"Description": "gulaman"
},
{
"Concept": "9",
"Description": "sisig"
},
{
"Concept": "12",
"Description": "noodle"
},
{
"Concept": "15",
"Description": "sisigan"
},
{
"Concept": "16",
"Description": "buko shake"
},
{
"Concept": "17",
"Description": "mango shake"
},
{
"Concept": "19",
"Description": "burger"
},
{
"Concept": "20",
"Description": "sample"
},
{
"Concept": "21",
"Description": "shit"
}
]
}
How do I get only "Description":"siopao"? I'm using AngularJS.
If you want to map the jsonstring to something like:
["siopao", "gulaman", "sisig", "noodle", "sisigan", "buko shake", "mango shake", "burger", "sample", "shit"]
use
var object = JSON.parse(jsonString);
var descriptions = object.Concepts.map(function(c) {
return o.Description;
});
If you only want the one with the description "siopao", add a filter before the map:
var object = JSON.parse(jsonString);
var description = object.Concepts.filter(function(a) {
return a.Description === "siopao";
}).map(function(c) {
return o.Description;
})[0];

Angular Differences Between Two Models

I have an angular application which uses a significantly large shared model. Currently, when a user presses save the entire model is posted to a RESTful service. Ideally I would only like to post the fields that have changed. Since this is a shared model I do not have access to form validation states such as dirty/pristine etc. The idea I can think of is to have two models, the original and the modified and compare these.
Original Model
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"id": "123",
"number": "212 555-1234"
},
{
"id": "456",
"number": "646 555-4567"
},
{
"id": "789",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
Changed Model
{
"firstName": "Jane",
"lastName": "Smith",
"isAlive": true,
"age": 50,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"id": "123",
"number": "1234567890"
},
{
"id": "456",
"number": "646 555-4567"
},
{
"id": "789",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
Data Posted - This is what I need!
{
"firstName": "Jane",
"age": 50,
"phoneNumbers": [
{
"id":"123",
"number": "1234567890"
}
]
}
How can I achieve this? I need the changed fields including any fields called id!
You'll need something like this. Working Fiddle: https://jsfiddle.net/jyyyLaot/
function filter(obj1, obj2) {
var result = {};
for(key in obj1) {
if(obj2[key] != obj1[key]) result[key] = obj2[key];
if(typeof obj2[key] == 'array' && typeof obj1[key] == 'array')
result[key] = arguments.callee(obj1[key], obj2[key]);
if(typeof obj2[key] == 'object' && typeof obj1[key] == 'object')
result[key] = arguments.callee(obj1[key], obj2[key]);
}
return result;
}

Resources