This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Chrome and probably Opera sort object properties automatically
I have a very simple code:
var obj = {3:'a',2:'b',1:'c'};
console.log(obj);
In Firefox 4.0.1 it returns:
Object { 3="a", 2="b", 1="c"}
In Chrome 11.0.696.71 it returns:
Object { 1="c", 2="b", 3="a"}
How can I coerce Chrome doesn't sort this object?
For Objects the spec is that the order of elements is not preserved. In other words javascript doesn't guarantee any particular order for the properties of an Object.
You'll have to use an array if you want to preserve the order of elements. In this case, your Object can be rewritten to:
var arrobj = ['c','b','a'];
or
var arrobj = ['a','b','c'].reverse();
Where you have take into account that the first element index will be 0 (zero)
It's a known "bug"/feature of chrome. Even author of jQuery indignant of this, but chrome guys stay inflexible, saying that this is a "feature":
http://code.google.com/p/chromium/issues/detail?id=883 [1]
As a workaround use arrays or some kind of MixedCollection (as in extjs) or something similar.
null !== true and also null !== false // in php and js it's so
[1]: John Resig (jeresig) is an author of jquery
Related
This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}
members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}
This question already has answers here:
What is "undefined x 1" in JavaScript?
(5 answers)
Closed 4 years ago.
Some of the common things asked is , why Array appears to be zero even if there's content inside. My question now is a bit weird. Why am I seeing
(66) [empty × 65, {…}]
in chrome console even if the array has at least 1 array value inside ?
That is what you see when you have a sparse array - with some indicies defined, but some indicies lower than the defined indicies not defined (or ever assigned to), for example:
const arr = [];
arr[65] = 'foo';
console.log(arr);
(look at the results of these two snippets in the browser console, snippet console won't be visible)
Note that this is different from having literal undefined values in the first 65 indicies, which will be shown as undefined rather than empty:
const arr = new Array(65).fill(undefined);
arr[65] = 'foo';
console.log(arr);
Sparse arrays are almost never a good idea, though - if you ever see this, it's an indication that you should probably fix the code to avoid the sparse arrays. Consider another structure instead, perhaps an object with numeric keys:
const obj = {
'65': 'foo'
};
A programmer will expect an array to be an ordered collection of elements - what would it mean for a collection to not have any value at all at the top of an ordered collection (not just undefined, but not any value)? It just doesn't make much sense - while possible, such constructs are not what arrays are for.
As Kaiido notes, empty elements will not be iterated over with array methods like forEach:
const arr = [];
arr[65] = 'foo';
arr.forEach((item, i) => {
console.log(item, i);
});
Which makes a bit of sense, but it's still unintuitive (would you have been sure of this without trying the code yourself or looking up the spec?). One would usually expect the first iteration of a forEach callback to have an index of 0.
It's just 65 empty elements, it's can be if you create array like this:
const arr = Array(65);
arr.push(1);
console.log(arr)
or in new Array set new element on some index;
const arr = [];
arr[65] = 1;
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
If my json is this:
[
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
]
How to parse this in javascript. I am looking for some for loop kind of solution which can iterate over the json and can give me "cat1 ", "cat2" etc.
P.S.: My json list is dynamic which i am getting from some source. So, i dont know how my json elements are there and what are the fields.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
try this.
var list= [
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
];
list.forEach(function(item){
console.log(item[0]);
});
This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
As an example, how would I determine if "component" is in the array below?
["component.part", "random-component", "prefix-component-name", "component"]
Update:
It seems like my use of false positive was misleading. I meant that it would say that component was in there 4 times, when I want to match the string by itself.
ie. It should return false when checking for the presence of "component" in the below array.
["component.part", "random-component", "prefix-component-name"]
Use the Array.find API.
Example:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
For more usage example.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
One way is to use .find() to get the string you want from the Array.
Try using $.inArray() method.
var list=["component.part", "random-component", "prefix-component-name", "component"];
if($.inArray(" component",list) != -1){
console.log("Item found");
}
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
false positives? Array.prototype.indexOf and Array.prototype.includes both use strict equality which makes that impossible here.
IndexOf won't give you false positive. It will give you 3. If you want to find all elements that has "otherstuff componenet" you can loop through your array and check with String.includes()
Here is a beginner friendly solution.
var arr = ["component.part", "random-component",
"prefix-component-name", "component", "asdf"];
console.log(arr.indexOf('component')); // give u 3
for (var i = 0; i < arr.length; i++){
if (arr[i].includes('component')){
console.log(arr[i]);
}
}
This question already has answers here:
JSON find in JavaScript
(7 answers)
Closed 7 years ago.
I receive data as a JSON object, like this:
[{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}]
I know I can access the data like this:
alert(obj[0].amount);
But I would like to be able to access the data like this:
obj[transid].amount
where transid is a previously declared and assigned variable, like this:
var transid = 1091;
alert(obj[transid].amount); //returns -549
If this is even possible, I assume the JSON object would have to be restructured (I don't have any control over how I receive the JSON object), but I don't really have any idea how to go about this. I've tried Googling and SOing, but I am just not sure what to look for.
Edit: I've looked at the proposed duplicate question as suggested by Travis J, and I do not agree that this is a duplicate. I'm not asking to loop through data. I'm asking for methods to reference by a specific index, given JSON that I don't control how it comes to me. The accepted answer in the proposed duplicate shows how I envision the code to look (in the second code box), but I don't think it really answers my question. Another answer in the proposed duplicate, posted by Hakan Bilgin, suggests using defiantjs, which would probably work. However, there are many other methods, some of which have been provided as answers to this question already.
You can use filter like
obj.filter(function(o){
return o['transid'] === 1091;
})[0].amount // -549
You can add the above function to Array's prototype like
Array.prototype.get = function(id){
return Array.prototype.filter.call(this,function(obj){
return obj['transid'] === id;
})[0].amount
}
And use it like
obj.get(1091); // -549
It is up to you to add proper validation like dealing with not found keys and duplicates.
You can create a new object from that one. Something like this
var transactionArray = [
{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}
];
var transactionsById = {};
transactionArray.forEach(function(element) {
transactionsById[element.transid] = element;
});
var transid = 1091;
alert(transactionsById[transid].amount); //returns -549
Where transactionArray is what you refer to as obj in your question.