Calulating length in Javascript [duplicate] - javascript

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 8 years ago.
Below is my object in JavaScript, how can i calculate the length of it.
var treeObj = {
1: ['96636736','10'],
2 : ['96636734','20'],
3 : ['96636731','45']
};
treeObj .length is not working. any help would be appreciated. Thanks.

You can do this:
Object.getOwnPropertyNames(treeObj).length; // 3
getOwnPropertyNames returns array of properties of treeObj whose length can be checked.

To count the number of properties an object has, you need to loop through the properties but remember to use the hasOwnProperty function:
var count = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
count++;
}
}
If you forget to do that, you will be looping through inherited properties. If you (or some library) has assigned a function to the prototype of Object, then all objects will seem to have that property, and thus will seem one item "longer" than they intrinsically are.
consider using jQuery's each instead:
var count = 0;
$.each(obj, function(k, v) { count++; });
OR simply,
for (var p in obj)
count++;
UPDATE With current browsers:
Object.keys(someObj).length
Refer Old Post

Related

Using an empty object as a parameter to a conditional if loop [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
This is similar to what I have been trying to do,
var obj = {};
if(obj){
//do something
}
What i want to do is that the condition should fail when the object is empty.
I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.
You could use Object.keys and check the length of the array of the own keys.
function go(o) {
if (Object.keys(o).length) {
console.log(o.foo);
}
}
var obj = {};
go(obj);
obj.foo = 'bar';
go(obj);
You can check if the object is empty, i.e. it has no properties, using
Object.keys(obj).length === 0
Object.keys() returns all properties of the object in an array.
If the array is empty (.length === 0) it means the object is empty.
You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.
working example
var myObj = {};
if(Object.keys(myObj).length>0){
// will not be called
console.log("hello");
}
myObj.test = 'test';
if(Object.keys(myObj).length>0){
console.log("will be called");
}
See details of Object.keys

how to parse string to javascript object selector [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I want to parse a string to an object object selector like so :
var test = 'object.prop1.prop2';
into
object['prop1']['prop2'];
The problem is i don't know how many properties the string could have.
What is the best way to to parse a string accross, idealy without something like json parse/ eval?
There is a package for that :
https://www.npmjs.com/package/object-path
Juhana's link is excellent, but also a bit more of a complex problem than the one you have here. Here is my take (https://jsfiddle.net/gm32f6fp/3/):
var object = {
prop1: {
prop2: {
foo: 1
}
}
};
function get(object, key) {
var keys = key.split('.');
for (var i = 0; i < keys.length; i++) {
if (!object.hasOwnProperty(keys[i])) {
return null;
}
object = object[keys[i]];
}
return object;
}
console.log(get(object, 'prop1.prop2'));
console.log(get(object, 'prop1.prop3'));
The idea is to take the string of keys, split it based on the dot. Then you have an arbitrarily large array of keys, so we take each key, one by one, and dive into the object. (If we end up at a dead end, we bail out.)

TypeError: this.reduce is not a function [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 3 years ago.
After adding a method to the Array prototype, some other, unrelated script breaks.
[Opera] Unhandled Error: 'this.reduce' is not a function
[Firefox] TypeError: this.reduce is not a function
The method itself works ([1,2,3].xintsum() outputs 6 as expected).
// adding a function to the Array prototype
Array.prototype.xintsum = function() { return this.reduce(function(old, add) {return old + add;}, 0); };
// accessing the array in a way that worked before
$(document).ready(function (){
var some_array = [];
for (head_n in some_array) {
var v = some_array[head_n];
$('<th></th>').text(v);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is happening because you are using for..in on an array. You shouldn't be doing that.
When you added Array.prototype.xintsum, you added a xintsum property to every array. So, what happened was, that your for loop iterated over that property of your array.
The value of this property is a function. When you pass a function to .text(), jQuery will call it like this:
v.call(ele, index text);
It's setting this to the element. And well, DOMElements don't have .reduce functions.
You need to loop like this:
for(var i = 0; i < some_array.length; i++){
var v = some_array[i];
}
This code:
var v = some_array[head_n];
$('<th></th>').text(v);
when it gets to xintsum is the same as this:
$('<th></th>').text(function() {
return this.reduce(function(old, add) {
return old + add;
}, 0);
});
When a function is passed to text, the function is called once for each element contained in the jquery object which it is called on. For each call this refers to that dom element. In this case, the th you have created. Therefore, the error message is letting you know that th has no such function.
v() is being called in the context of the <th> element, not an array. Hence, the <th> doesn't have a method reduce(). This is because for ... in iterates over non-numeric properties just as much as numeric properties. I would recommend using some_array['head'].forEach() instead.

Alternative to eval for multiple property lookup [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 8 years ago.
I have a a function that takes a string like "obj.key.subkey.subsubkey":
function(obj, key) {
return eval('obj.'+ key);
}
What would be a safe alternative to eval in this case or is eval fine? new Function won't work in this case AFAIK. Maybe split and loop then?
I'm not sure you really need a function here. If you have the object and the key just use the key to return the property on the object.
obj[key]
If you must handle multiple keys:
function get(obj, key) {
var keys = key.split(".");
var tmp = obj;
for (var x = 0; x < keys.length; x++){
tmp = tmp[keys[x]];
}
return tmp;
}
Working Example: http://jsfiddle.net/H55ka/

How to check whether a given string is already present in an array or list in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

Categories

Resources