JavaScript code issue : I am converting object to array - javascript

I am converting JavaScript object to array but in result I am getting one null
here my code
<div id="a"></div>
Object.prototype.toArray = function(){
var arr = [];
for (var i in this) {
arr.push(this[i]);
}
return arr;
}
var providers = {
facebooklike: "Facebook Like",
facebookrecommend : "Facebook Recommend",
facebooksend : "Facebook Send",
twittertweet : "Twitter Tweet",
linkedinshare : "LinkedIn Share",
linkedinrecommend : "LinkedIn Recommend",
googleplusplusone : "Google+ +1",
googleplusshare : "Google+ Share"
};
var a = document.getElementById("a");
a.innerHTML = JSON.stringify(providers.toArray());
My result is
["Facebook Like","Facebook Recommend","Facebook Send","Twitter
Tweet","LinkedIn Share","LinkedIn Recommend","Google+ +1","Google+
Share",null]
Here is fiddle example

Add check for own properties (not inherited from the Object proptotype):
Object.prototype.toArray = function(){
var arr = [];
for (var i in this) {
if(this.hasOwnProperty(i))
arr.push(this[i]);
}
return arr;
}

Add hasOwnProperty check.
for (var i in this) {
if (this.hasOwnProperty(i)) {
arr.push(this[i]);
}
}

Related

How to create a unique array which has objects as elements?

I have an array of students and I want to create an unique array of this students. Each student has a unique id value and I want to compare with this id value.
Here is a Student object;
{
"id" = "3232aab1",
//some other properties
}
var Students =[
{
"id" : "3232aab1" //some other properties
} ,
{
"id" : "3232aab1" //some other properties
},
{
"id" : "3232aab2" //some other properties
} ,
{
"id" : "3232aab3" //some other properties
} ,
{
"id" : "3232aab2" //some other properties
} ];
var tmpObj = {};
var uniqArray = Students.reduce(function(acc,curr){
if (!tmpObj[curr.id]){
tmpObj[curr.id] = true;
acc.push(curr)
}
return acc;
},[]);
console.log(uniqArray);
var a=[];
a.push({id:1,name:"something"});
// repeat similar;
To access an id
a[index].id;
Sample code to search
var elem = 1; // id to be searched
//loop
for(var i=0; i<a.length; i++){
if(elem == a[i].id){
break;
}
}
// now a[i] will return the required data {id:1,name:"something"}
// a[i].id = > 1 and a[i].name => something
I'd probably take an approach similar to this...
class Students extends Map {
set(key, value) {
if (this.has(key)) { throw new Error('Student already there'); }
return super.set(key, value);
}
}
const students = new Students();
students.set(1, { name: 'Peter' });
console.log(students.get(1));
// students.set(1, { name: 'Gregor' }); this throws
If you have underscore, you can use the following
ES6
_.uniq(Students, student=>student.id)
ES5
_.uniq(Students, function(student){return student.id;})

AngularJs - check if value exists in array object

var SelectedOptionId = 957;
$scope.array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}]
Is there a way of checking if a value exists in an that kind of array objects. I am using Angular and underscore.
I have tried all this -
if ($scope.array.indexOf(SelectedOptionId) === -1) {console.log('already exists')}
and
console.log($scope.array.hasOwnProperty(SelectedOptionId)); //returns false
and
console.log(_.has($scope.array, SelectedOptionId)); //returns false
You could use Array#some and check with in operator.
exists = $scope.array.some(function (o) {
return SelectedOptionId in o;
});
Check this
function checkExists (type) {
return $scope.array.some(function (obj) {
return obj === type;
}
}
var chkval=checkExists("your value")
Try this:
if($scope.array[SelectedOptionId] || _.includes(_.values($scope.array, SelectedOptionId))) { }
That should cover both a key and a value.
let selectedOptionId = "957";
let array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
let filtered = array.filter(function(element){
return Object.keys(element)[0] === selectedOptionId;
});
console.log(filtered);
console.log(_.some($scope.array, function(o) { return _.has(o, "957"); }));
using underscore
You can use filter for this. The following code should return you output array with matching results, if it exists, otherwise it will return an empty array :
var array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var SelectedOptionId = 957;
var result = array.filter(
function(item) {return item[SelectedOptionId]}
)
console.log(result);
For your input it returns:
[ { '957': '1269' }, { '957': '1269' } ]
You can do it using the in operator or the hasOwnProperty function, to check for the existence of a key in an object inside the given array.
The way you've tried using hasOwnProperty function didn't work because you were checking it directly on the array instead of checking against the items in the array.
Check the below code snippet.
angular
.module('demo', [])
.controller('HomeController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [{
"957": "1269"
}, {
"958": "1265"
}, {
"956": "1259"
}, {
"957": "1269"
}, {
"947": "1267"
}];
var key = '957';
var isExists = keyExists(key, vm.items);
console.log('is ' + key + ' exists: ' + isExists);
function keyExists(key, items) {
for (var i = 0; i < items.length; i++) {
// if (key in items[i]) {
if (items[i].hasOwnProperty(key)) {
return true;
}
}
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="HomeController as home">
{{home.items | json}}
</div>
</div>
Different ways to do this :
Using Object hasOwnProperty() method.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
function checkOption(key) {
for(var i in arrayObj) {
if(arrayObj[i].hasOwnProperty(key) == true) {
return key+" exists.";
} else {
return key+" Not exists.";
}
}
};
console.log(checkOption(SelectedOptionId)); // 957 exists.
using Array filter() method.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var result = arrayObj.filter(function(elem) {
return elem[SelectedOptionId]
});
if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}
using Array some() method as suggested by Nina Scholz.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var result = arrayObj.some(function (o) {
return SelectedOptionId in o;
});
if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}

How to use unique filter in controller in AngularJS

I would like to filter an array by unique category in controller and then use the filtered array with ng-repeat in html page. My array is:
$scope.tabs = [
{OBJECTID:1, TYPES:8, Category:"Pharmacies",Name_EN:"antonis" , text : "Home"},
{OBJECTID:2, TYPES:8, Category:"Opticians",Name_EN:"antonis" , text : "Games"},
{OBJECTID:3, TYPES:8, Category:"Doctors", Name_EN:"antonis" , text : "Mail"},
{OBJECTID:4, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Car"},
{OBJECTID:5, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Profile"},
{OBJECTID:6, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Favourites"},
{OBJECTID:7, TYPES:8, Category:"Pharmacies",Name_EN:"antonis" , text : "Chats"},
{OBJECTID:8, TYPES:4, Category:"Sights",Name_EN:"antonis" , text : "Settings"},
{OBJECTID:9, TYPES:4, Category:"Meuseums",Name_EN:"antonis" ,text : "Home"},
{OBJECTID:10, TYPES:4, Category:"Meuseums",Name_EN:"antonis1" , text : "Home"}
];
the filtered array will be like this:
$scope.FilteredArray = [
{Category:"Pharmacies"},
{Category:"Opticians"},
{Category:"Doctors"},
{Category:"Clinics"},
{Category:"Sights"},
{Category:"Meuseums"},
];
Thanks in advance.
Use unique filter inside controller and apply ng-repeat on filtered array
//Filtered array
$scope.filteredArray = $filter('unique')($scope.tabs,'Category');
<ul>
<li ng-repeat="tab in filteredArray">{{tab.Category}}</li>
</ul>
Filter
angular.module('myapp').filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
FULL EXAMPLE
You can also do it without angular filter. If you have used lodash module in your angular application then you can simply do it with below lodash function. It will return uniq records by whatever key you want.
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
You can do this too,
$scope.unique = {};
$scope.distinct = [];
for (var i in $scope.tabs) {
if (typeof($scope.unique[$scope.tabs[i].Category]) == "undefined") {
$scope.distinct.push($scope.tabs[i].Category);
}
$scope.unique[$scope.tabs[i].Category] = 0;
}
DEMO
That code could be used to create a method this will give you an array of strings also you can modify to create object array -
var flags = [], $scope.FilteredArray= [], l = $scope.tabs.length, i;
for( i=0; i<l; i++) {
if( flags[$scope.tabs[i].Category]) continue;
flags[$scope.tabs[i].Category] = true;
$scope.FilteredArray.push($scope.tabs[i].Category);
}
Use the default unique filter:
<select ng-model="tab" ng-repeat="uni in tabs | unique:'Category'">
</select>

Search object with namespace / key

I'm trying to write a function that can look up a namespace and value in a JavaScript object and return the key.
Image this data:
var o = {
map: {
lat : -33.86749,
lng : 151.20699,
zoom : 12
},
filters : {
animals : {
dogs: {
myDog : 'fido'
}
}
}
};
function get(namespace, key){
//TODO
}
get('filters.animals.dogs', 'myDog')
How would you build a function that does this dynamically - no matter the depth of the namespace?
This function is somewhat close, only it modifies the original object which we don't want ofcourse:
var get = function(obj, namespace, key, value) {
var parts = namespace.split('.');
for(var i = 0; i < parts.length; i++) {
if(typeof obj[parts[i]] == 'undefined'){
obj[parts[i]] = {};
}
obj = obj[parts[i]];
}
return obj[key] = value;
};
Reason for the madness is that I cannot expose the object. It must remain private and a public method must spit out a result.
Give this a try.
function get(namespace, key) {
var parts = namespace.split('.'),
i = 0,
l = parts.length,
obj = o;
while ( i < l ) {
obj = obj[parts[i]];
if ( ! obj ) break;
i++;
}
return obj && obj[key] ? obj[key] : null;
}
I have created a fiddle with working code. Hope that helps.
http://jsfiddle.net/RdhJF/2/
var o = {
map: {
lat : -33.86749,
lng : 151.20699,
zoom : 12
},
filters : {
animals : {
dogs: {
myDog : 'fido'
}
}
}
};
function get(obj, namespace)
{
var parts = namespace.split('.');
if(parts.length==0)
return -1;
var previousValue = obj;
for(var i = 0; i < parts.length; i++)
{
if(typeof previousValue[parts[i]] == 'undefined')
return -1;
else
previousValue = previousValue[parts[i]];
}
return previousValue;
}
var myValue= get(o,'filters.animals.dogs.myDog');
alert(myValue);

split a javascript object in to a key value array

Trying to split a javascript object in to a hash array.. I have to split the contents inside the array based on the occurrence of symbol"|"
my input array looks like
{
"testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
},
"data": [
"4|Sam|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
and the expected output is [{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "0"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]
This is what I've tried.. but it is not complete.
http://jsfiddle.net/Dwfg6/1/
var header = responseData.header.testFieldNames,
length = header.length,
result;
result = responseData.data.map(function(el) {
var ret = {}, data = el.split('|'), i;
for (i=0; i < length; i++) {
ret[header[i]] = data[i];
}
return ret;
});
console.log(result);
The demo. (Note: you may use jQuery.map methods instead for old browsers.)
You were close...
http://jsfiddle.net/Dwfg6/4/
var responseData = {
"header": {
"testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
},
"data": [
"4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
function buildData(fields, data) {
var output = [];
if (fields && fields.length && data && data.length) {
for (var i = 0; i < data.length; i++) {
var row = data[i].split("|");
output[i] = {};
while (row.length) {
output[i][fields[4 - row.length]] = row.shift();
}
}
}
return output;
}
console.log(buildData(responseData.header.testFieldNames, responseData.data));
fiddle : http://jsfiddle.net/FjJse/1/
My answer:
fiddle
function mapData (data) {
'use strict';
var result=[];
var i, j;
var values = [];
var resultObj;
for(i=0; i < data.testFieldValues.length; i += 1) {
values = data.testFieldValues[i].split("|");
resultObj = {};
for(j = 0; j < data.testFieldNames.length; j += 1) {
resultObj[data.testFieldNames[j]] = values[j];
}
result.push(resultObj);
}
return result;
}
//$(document).ready(function() {
// 'use strict';
var data = {testFieldNames: ["testNumber", "testName", "testDate1", "testDate2"],
testFieldValues: [
"4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
console.log(mapData(data));
//});
/*Expected Output [{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "2012-02-10T00:00Z"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]*/
Hit F12 in Chrome to see console, or open FireBug in FireFox or LadyBug in Opera, etc.

Categories