For me i have a object like var object = [{"1":"w"},{"2":"z"}] ;
While iterating other array = '[{},{},{}]' i wanted to get object key and value i.e processing at index 0 of array should give me 1 and w respectively .
. While seeing some other posts of stack overflow i tried with ,
$.each(array, function(index, value) {
if(object[index] != undefined)
{
console.log("enterobject",$.parseJSON(JSON.stringify(object[index])));
console.log("enterobjectValue",$.parseJSON(JSON.stringify(object[index])).key);
console.log("enterobjectValue",$.parseJSON(JSON.stringify(object[index])).value);
}}
Only first console.log is printing like {"1":"w"} for index 0 , but not second and third log which i wanted to return me 1 and w respectively are not working .
Thanks
It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):
$.each(result[0], function(key, value){
console.log(key, value);
});
If you might have more than one element and you'd like to iterate over them all, you could nest $.each():
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
Related
How can ı equalize my array ıd and my value ıd and access value.name I didn't do it
This is my code:
activity(val) {
var act = this.items.map(function (val) {
if (element.ActivityID== val) {
return element.ActivityName
}
return act
});
Perhaps this?
activity (val) {
const activity = this.items.find(item => item.ActivityID === val)
return activity && activity.ActivityName
}
This just finds the item with the corresponding ActivityID and then returns its ActivityName.
Your original code contained several possible mistakes:
Two different things called val.
element doesn't appear to be defined.
The return act was inside the map callback. The activity method itself wasn't returning anything.
Not really clear why you were using map to find a single item. map is used to create a new array with the same length as the original array with each item in the new array determined by the equivalent item in the original array. It 'maps' the items of the input array to the items in the output array.
I have a array variable viewedprofiles= []; initialized.
I'll be assigning the profiles that have been viewed to this viewedprofiles array. Now if I try to display it (By assigning it to a $scope), I get NULL for other values that have not got assigned or touched.
var viewedprofiles= [];
angular.forEach(profiles, function(value, key){
if(value.viewed== "yes") {
viewedprofiles[value.id] = TRUE;
}
});
The output of viewedprofiles is as follows
[NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,TRUE]
Output explanation :
Since the 9th id's profile viewed value was yes, the output returned TRUE at the 9th element of the viewedprofiles array.
Nothing wrong actually.
But I was wondering as far as the above code, the id was TRUE for 9th element. What if the id was some large number say 15640, Will there be 15639 NULLs before TRUE? Am I doing anything wrong or is there another way to work this out?
I found the answer.
What I was trying to do was basically wrong at the assigning part. I should push the element instead of assigning.
The following worked.
angular.forEach(profiles, function(value, key){
if(value.viewed== "yes") {
viewedprofiles.push(value.id);
}
}, viewedprofiles);
In my Angular controller, i loop through an array of cities to retrieve each value sent :
angular.forEach($scope.outPutcities, function (value, key) {
// value.id are 3,4
$scope.countries.cityId = value.id;
$scope.cities.push($scope.countries.cityId)
});
But the cityId value has always the last value in the array which is 4.
[Object { countryName=Canada, cityId=**4**}, Object {countryName=Canada, cityId=**4**]
But what i want is :
[Object { countryName=Canada, cityId=**3**}, Object {countryName=Canada, cityId=**4**]
Is there an easy to fix this ? Thanks
Firstly this is redundant
$scope.countries.cityId = value.id;
You are assigning to countries.cityId and overwriting it on each iteration, rather just do
$scope.cities.push(value.id)
Your code does look fine besides that, are you sure the $scope.outPutcities has the values you are expecting?
I haven't found anything on that in Swift. Have found how to find unique values on an array, but not this. Sorry if it sounds quite basic...
But I have the following array
var selectedValues = [String]()
And the following value that comes from a Parse query
var objectToAppend = object.objectForKey("description")! as! String
this is how I'am doing it at the moment.
self.selectedHobbies.append(objectToAppend)
But because the query happens repeated times, it ends up appending repeated values. It works, but I just want to not waste memory and only keep unique values.
Any ideas on how to solve that in swift?
You can use a Set which guarantees unique values.
var selectedValues = Set<String>()
// ...
selectedValues.insert(newString) // will do nothing if value exists
Of course, the elements of a Set are not ordered.
If you want to keep the order, just continue with the Array but check before you insert.
if !selectedValues.contains("Bar") { selectedValues.append("Bar") }
I guess that your problem was resolved but I add my answer for next developers who's facing same problem :)
My solution is to write an extension of Array to add elements from an array with a distinct way:
here the code :
extension Array{
public mutating func appendDistinct<S>(contentsOf newElements: S, where condition:#escaping (Element, Element) -> Bool) where S : Sequence, Element == S.Element {
newElements.forEach { (item) in
if !(self.contains(where: { (selfItem) -> Bool in
return !condition(selfItem, item)
})) {
self.append(item)
}
}
}
}
example:
var accounts: [Account]
let arrayToAppend: [Account]
accounts.appendDistinct(contentsOf: arrayToAppend, where: { (account1, account2) -> Bool in
return account1.number != account2.number
})
my code is like this :
var arr = [];
arr.push(item1,item2);
so arr will contain like:
["name","thing1"]
But i got problem when pushing element with same exact value, how do i filter same element value but still accepting update/changes. JSFIDDLE
You can use arr.indexOf which returns -1 if it is not found, so you can add it then.
e.g.
if (arr.indexOf(item) == -1) {
arr.push(item);
}
However, this does not work in old browsers...
JQuery has a method ($.indexOf) that works in every browser, even very old ones.
Just javascript is enough.
If an array contains the item its index is >= 0
so you can do this, if index == -1 , item does not exist in the array, so you can push unique item
if(arr.indexOf(item) == -1) {
arr.push(item);
}
Edit:
You asked for changing the number, this is how
var index = arr.indexOf(item);
if(index > -1) { //checking if item exist in array
arr[index]++; // you can access that element by using arr[index],
// then change it as you want, I'm just incrementing in above example
}
As what most of the answers have pointed out, you can use the Array.prototype.indexOf() method to determine if a value exists or not. In order to check for this, check the array of strings against your ng-models value property, selects.value, within the ng-change() event callback.
DEMO
Javascript
$scope.goChange = function(name, value){
if(!~arr.indexOf(value)) {
arr.push(name, value);
console.log(arr);
}
};
HTML
<select ng-model="selects" ng-change="goChange(item.name, selects.value)" ng-options="i as i.value for i in options">
<option value=""></option>
</select>
You should use Angular Filters.
Some implementations can be found as answers to a similar question: How to make ng-repeat filter out duplicate results
To filter duplicates in an array (es6):
let arr = ['foo', 'foo', 'bar', 'baz'];
Array.from(new Set(arr));
console.log(arr);
// ['foo', 'bar', 'baz'];