How to convert object into array in angularjs Ionic - javascript

Let's say I have an object that looks like this: {first: "asdasd", second: "asdas", third: "dasdas", four: "sdasa"}
I need to convert this object into array.
if(values){
var first=values.first;
var second=values.second;
var third=values.third;
var four=values.four;
var five=values.five;
var six=values.six;
var seven=values.seven;
var eight=values.eight;
var nine=values.nine;
var ten=values.ten;
if(first){
userData.push(first);
}
if(second){
userData.push(second);
}
if(third){
userData.push(third);
}
if(four){
userData.push(four);
}
if(five){
userData.push(five);
}
if(six){
userData.push(six);
}
if(seven){
userData.push(seven);
}
if(eight){
userData.push(eight);
}
if(nine){
userData.push(nine);
}
if(ten){
userData.push(ten);
}
console.log(userData);
I am currently doing by this code but i think it is the wrong approach. So how could i change this to array that looks like ["asdasd", "asdas", "dasdas", "sdasa", "asdasd", "asdas", "dasdas", "sdasa"].
In ionic drag and drop directive doesnot work when i use object in ng-repeat.And works perfectly when i apply array to ng-repeat.

There are several ways you could do it.
One would be using Object.keys:
Object.keys(values).forEach(function(key) {
userData.push(values[key]);
});
You could also use for ... in like this:
for (var key in values) {
userData.push(value[key]);
}
If your object has any properties inherited from prototype then it would also show, so you do need to check if property really belongs to this instance:
for (var key in values) { //proper way to iterate keys using for..in
if(values.hasOwnProperty(key)) {
userData.push(value[key]);
}
}
Since you're using angular, you could also use angular.forEach:
angular.forEach(values, function(value){
userData.push(value);
});
and I think this is the cleanest solution for you.

I would suggest using javascript library underscorejs or lodash for this kind of array and objects manipulation and iteration ,as it seems to be most preferable way of doing it ,keeping your code clean.
Its a simple javascript file that you can include in your project and you don't have to do any complex thing to make it work.Just plug and play.
If you do include underscore/lodash ,all you have to do is :-
var mycoll = _.values(yourobjectvariable);
This will fetch all the values in that object and convert it into an array automatically for you.
http://underscorejs.org/#values
Or if you want to do it with plain javascript , i think the above Randall Flag's answer is suffice for it.

`
if(values)
{
Object.keys(values).forEach(function(key) {
userData.push(values[key]);
});
}
`
Sometimes instead of a simple solution we think too much and end up with complex time taking solution ,which we can achieve with small simple code

Related

Trying to get the"name" of a javascript object supplied by an API

I am calling an API which is giving me back, among other things, an array of javascript objects. The objects in the array are named and I need to use the name in the new individual objects I am creating from the array. Problem is, I don't know how to get to the object's name.
{
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
I am after the "OldCrowMine.E9001" bit. I am sure this is quite simple, I just don't know how to search for the answer because I am not sure what to call this. I have tried searching for a solution.
Just loop - or am I missing something? Simplified raw data version.
var raw = {
"OldCrowMine.E9001":{"share":1524883404},
"OldCrowMine.S9001":{"share":1524}
};
for(var first in raw) {
console.log(first +" share -> "+ raw[first]["share"]);
}
var obj = {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
console.log(Object.keys(obj)[0]);
Get the keys and map the name and the object:
var x= {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
};
var mapped = Object.keys(x).map(function(d,i){return [d,x[d]]});
The name is map[n][0] and its object is map[n][1] where n is your item number.

AngularJS soltuion to determining if any element in array1 exists in array2

I am working on an angularJS widget (my first) and I currently am looking for an angularJS solution to my problem.
Basically I have one array containing a list of string values.
var array1 = [
"Need to Know",
"Test Category 2",
"News"
];
and another array containing another list of string values
var array2 = [
"need to know",
"release notes",
"NEWS"
];
I need a true statement if any element from one array matches any element from the other array. The result also needs to be case insensitive.
Here is my current solution and works great.
angular.module("myWidget", function(...){
// angular code here
})
.service('arrayService', function() {
function arrayToLowerCase(array) {
return array.join("~!~").toLowerCase().split("~!~");
}
function arrayElementIsInArray(array1, array2) {
for (var i in array1) {
if (array2.indexOf(array1[i]) >= 0) {
return true;
}
}
return false;
}
function arrayCompare(array1, array2) {
return arrayElementIsInArray(arrayToLowerCase(array1), arrayToLowerCase(array2));
}
return {
arrayToLowerCase: arrayToLowerCase,
arrayElementIsInArray: arrayElementIsInArray,
arrayCompare: arrayCompare
};
})
the problem is my javascript coders (I primary work in c#) feel there is a more angularJS way to do this but they have brought nothing to the table as a definitive solution. It was suggested that the $filter module might be useful but I didn't see how it would exactly solve my problem.
If I already have the best solution, then awesome. If not please let me know what you think and lets go from there.
Thanks in advance.
EDIT: In response to some of the answers, I felt that I might have misinterpreted my request. What I am asking is there a built in function that angular provides that does this out of the box?
After researching this a bit more; the $filter Module will probably do it with a custom comparater implemented but that seems like way overkill for what I am looking for.
The current responses are all good stuff though. Thanks again!
Absolutely nothing to do with Angular. This is plain data structures and data manipulation. To say there should be a more AngularJS way of doing it would be like saying there should be a more MVC way to add two numbers.
Angular provides no basic data structures and utility set of functions beyond what is available in your browser's native list of array functions, which is different depending on which ECMAScript standard the browser supports.
You may want to look into a library like Lo-Dash for stuff like this (which you can use right along with Angular with no problems) as it's preferable to have proven code for these kind of data manipulations than to constantly have to debug your own.
With Lo-Dash, and remembering the requirement for case-insensitivity:
var array1Lowered = _.map(array1, function (value) { return value.toLowerCase(); });
var anyMatchesBool = _.any(array2, function (value) {
return _.contains(array1Lowered, value);
});
Note that I'm making the assumption that there will be no non-string items in either array.
Lo-Dash normalizes the API so you don't need to worry about what functions each browswer supports. If there's a native function, Lo-Dash will use it because it's faster. If not, Lo-Dash provides an all-JavaScript implementation.
Try this on for size. To me this really has nothing to do with Angular
(function(array1, array2) {
var tlc = function(a) { return a.toLowerCase(); };
array2 = array2.map(tlc);
array1 = array1.map(tlc);
return array1.filter(function(n) {
return array2.indexOf(n) != -1;
}).length > 0;
})(array1, array2);
Using native functions...
var intersection = array1.filter(function(n) {
return array2.indexOf(n) != -1
});
With help from Simplest code for array intersection in javascript

JSON data to JavaScript

When I do JArray.toSource(), I get this:-
[{selectionID:"1", cnt:"5"}, {selectionID:"2", cnt:"2"}, {selectionID:"3", cnt:"1"}]
How can I convert JArray to format like this:-
[[1,5],[2,2],[3,1]]
in JavaScript.
Eventually I want newJArray.toSource() become [[1,5],[2,2],[3,1]]
You can use Object.keys which returns the keys, and map to map the array as such:
array.map(function(arrayItem) {
return Object.keys(arrayItem).map(function(objectKey) {
return +arrayItem[objectKey]; // convert to number
});
});
Basically, you replace each element in the array with the values of the object.
pimvdb's solution is very nice. My comment is that in this particular case this is enough:
array.map(function(arrayItem) {
return [arrayItem.selectionID, arrayItem.cnt];
});
It is uglier (more specific), but my gut feeling is that it's much more efficient (and sometimes that matters).

How do you get the number of keys in a JSON object?

I am creating a gallery plug-in in which I need to figure out the number of elements in a plain javascript object. The following is how I would like to be able to create the gallery.
$.Gallery.create($('#galContainer'), {
'img1.png': 'http://linktosomewhere/',
'img2.png': 'http://linktosomewhere/',
'img3.png': 'http://linktosomewhere/',
........
}, optionsObj);
This will put the images into the gallery with the corresponding links to some page when clicked. Currently I am using an array for that second parameter without the links and I am getting the length of the images using images.length. However using the notation above would be ideal for me and I need to be able to tell how many keys there are in this object.
I am aware of this post and a few others saying you can not get the number of elements in the object. If this is indeed the case, do you have any suggestions on another way to setup this function call which will be efficient and easy to use?
The code you see in the other question you linked to is really the only way to do it. Here's how you can create a function to do it:
function count(obj) {
var i = 0;
for (var x in obj)
if (obj.hasOwnProperty(x))
i++;
return i;
}
Can't you use an array of objects instead?
$.Gallery.create($('#galContainer'), [
{src:'img1.png', href:'http://linktosomewhere/'},
{src:'img2.png', href:'http://linktosomewhere/'},
{src:'img3.png', href:'http://linktosomewhere/'},
........
], optionsObj);
You should just add a .src and .href in your code to read it.
The way you designed your dataset as a simple hash is not very flexible for additional attributes(size, categories, selected, etc...)
Underscore.js has a method that will tell you how large the object is _.size(obj);
Object.prototype.count = function()
{
var c = 0;var i;
for(i in this){if (this.hasOwnProperty(i)){c++;}};
return c;
}
Personally I would build your own prototype for Object, you can use MyObject.length but I think its not fully supported by IE.
test reveal that the length variable is unavailable in Objects.
Testcase:
MyObject = {
a : '0',
b : '1',
c : '2'
}
if(MyObject.count() > 5)
{
$.Gellery.Error('Images','Only 5 images allowed'); //...
}
http://jsfiddle.net/b9Nwv/

getting variable/object elements and values in javascript

I'm not sure if I'm using the correct terminology, so please correct me if I'm not.
I've got a javascript variable which holds a group of values like this
var my_variables = {
first_var: 'starting',
second_var: 2,
third_var: 'continue',
forth_var: 'end'
}
Now I'm trying to get these variables in my script, but I don't want to have to check for each one.
Right now i'm doing this
if(my_variables.first_var!=null){
query=query+'&first_var='+my_variables.first_var;
}
if(my_variables.second_var!=null){
query=query+'&second_var='+my_variables.second_var;
}...
I'm hoping there is a simple way to recursively go through the object, but I haven't been able to find how to do that.
Something like
foreach(my_variables.??? as varName){
query=query+'&'+varName+'='+my_variables.varName;
}
Try this:
for(var key in my_variables)
query += '&'+key+'='+encodeURIComponent(my_variables[key]);
for (var varName in my_variables) {
query=query+'&'+varName+'='+my_variables[varName];
}
for (... in ...) is how you write this kind of loop in Javascript. Also use square brackets instead of a period when the field name is a value instead of the actual identifier, like here. Incidentally, I'd also suggest using window.encodeURIComponent if your values might contain arbitrary text.

Categories