Javascript shift() for Objects - javascript

So I want to take my list and add the first two (0 & 1) items together.
I tried this:
total=foo.shift();
foo[0]=total
And got this:
Uncaught TypeError: Object [object Array] has no method 'split'
I then tried to simply call "foo" and output it; same error.
This leads me to think that it is not in a form I can work with without some workaround.
Any help would be much appreciated. Thank you.

this is a working code that can help you:
//we initialize an array with two objects
var arr=[{'id':1,'nom':'ali'},{'id':2,'nom':'ahmed'}];
console.log(arr);
//array with two objects displayed in the console: [Object, Object]
//we call shift method
arr.shift();
console.log(arr);
//array with one object displayed in the console: [Object]

Related

Why do I need to use sometimes JSON.stringify and sometimes not

Sometimes in my project I'm using an JSON.Stringify to read data when I'm loging values to console, and sometimes I dont need to do it.. I'm wondering why?
In this example:
this._productServices.getAll().do(data => console.log(data)).subscribe(products=> this.articles= products);
And when I look at the console, there are values like this:
(4) [{…}, {…}, {…}, {…}]
Acctualy there is readable array of values.
But in this case:
filteredSubProducts: Group[];
filterSubProductsByIdId(Id) {
this.filteredSubProducts= this.articles.filter(item => item.parentId == Id);
console.log("Products array" + this.filteredSubProducts);
}
I get results as :
Products array[object Object],[object Object]
So I need to use JSON.stringify() in seconds case to get my values [object Object],[object Object] readable.. and I'm wondering why is that? Sometimes I'm using it and sometimes I'm not..
Thanks
You are getting it because you are adding a string "Products array" to an Array filteredSubProducts.
So the code is actually doing
console.log("Products array" + this.filteredSubProducts.toString());
The toString() method is causing the [object Object].
The way around it is to not concatenate, but use a comma in the console.log statement
console.log("Products array", this.filteredSubProducts)
Now it will allow you to show it without using JSON.stringify()
Now what is great about JSON.stringify() is it will give you the snapshot at that time. There are times when you change the array, object and it shows up in the console as the wrong value do to lazy evaluation. The stringify, causes it to be evaluated and you see it at that moment in time.
Because if you try to place an Object with a string Chrome will not parse the contents. If you need to "say" something before write an object or array to console you have to do it in two console commands or adding a comma
var myArray = [{content:"hola"}, {content:"hello"},{content:"hallo"}];
console.log("This does not work " + myArray);
console.log("This will work just ok");
console.log(myArray);
console.log("this works too" , myArray);
This is because you are joining together a string "Products array" with an object with .toString() - another string. What you see in console is string. Otherwise whole object gets logged. Try
console.log("Products array", this.filteredSubProducts);
Edit: Just removing the toString() does not do the trick, because everything that is after "string" + ... gets converted to string first.
// does not work
console.log("Products array" + this.filteredSubProducts);
That behaviour is called type coercion and you can read about it in this SO answer, in this article or just google it google it for more info
If you convert you response to JSON in your service, Then you have to stringify when you want to use that response.
res => res.json() // In this case you will need to use stringify
console.log() only works till 2nd level of nesting, for example if I run console.log({}, {}, {}), all of the objects in array will appear without any obfuscation, however if I try to log
console.log([
{},
{},
{a: {
a: {
a: {}
}
}}
])
The result will be something like [ {}, {}, { a: { a: [Object] } } ]
You can still view the objects by expanding them in any decent browsers console but terminals don't have that facility, so in order to view the nested items we use JSON.stringify() to convert the object and its children to string which can then be easily printed but you might have noticed they loosed their indentation in that way, because you are basically printing a string.

Correct way to access JavaScript object property

I do not see the error to access a property of this object:
console.log(routes);
[Object { bounds=((-34.76335, -58.21068), (-34.749880000000005, -58.202540000000006)), copyrights="Datos de mapas ©2016 Google", legs=[1], más...}]
console.log(routes.legs);
undefined
or console.log(routes["legs"]);
is similar: undefined
What am I doing wrong? Thanks
As your console printed out, routes is an array containing an Object, so you could try adding an index before selecting a key in the object.
So, for example:
console.log(routes[0]["legs"]);
// or
console.log(routes[0].legs);

AngularJS Removing Item from Array Leaves undefined in place of object

I have been working on an AngularJS project and have come across this issue before. I have the following array in my controller like so:
$scope.items = [];
I then fill this array with objects from a call to our REST API:
$http.get(API_URL_HERE).then(onSuccess);
The onSuccess method is called and the objects fill the array. I now have:
console.log($scope.items) resulting in [Object, Object, Object, ...]
Now when I use the $scope.items in an AngularJS ng-repeat loop it works great, as it should BUT if I try to remove an element from the $scope.items array, it always seems to remove the element BUT replaces it with an undefined value and this undefined value is interpreted by AngularJS in the ng-repeat loop and outputs an empty row in the template with no data. This causes issues if using ng-show / ng-hide for example as even though you have no real objects in the array, it still sees it as full because it is full of [undefined, undefined, undefined ...].
This is causing major headaches and I have seen other people with same issue but the fixes don't seem to work well.
The solution I have found to this, that seems to work well is below. Please also note that some people have said this is just a pure Javascript issue, well I don't think it is, when I tried it within AngularJS and pure Javascript, I got 2 different results with the same setup and data.
For example I have a $scope.remove method which handles removing items from the $scope.items array.
When I do the following code:
$scope.items.splice(index, 1);
It results in this console.log output [Object, Object, undefined, Object, ...].
However, by doing the following code:
$scope.items.splice(index, 1);
$scope.items.pop();
Results in the following output from console.log [Object, Object, Object] and my ng-repeat loop updates as it should without the empty rows.
My solutions seems to work fine but please do let me know if you find anything wrong with it. This code certainly looks cleaner than some of the others I have spotted on different sites and is working across all browsers I have tested.
UPDATE
My onSuccess method looks like this:
var onSuccess = function(response){
$scope.items = response.data.items;
//results in [Object, Object, Object, ...]
};
My $scope.remove method looks like this:
$scope.remove = function(index){
$scope.items.splice(index, 1);
//results in [Object, Object, undefined, Object, ...]
//add the following code
$scope.items.pop();
//results in [Object, Object, Object, ...] the undefined has gone
};
And only when adding in the pop method does it work as it should.

Javascript: splice strange behavior

I'm running a splice on an array like this, where the array has 5 elements:
array.splice(3, 0, newObj);
The splice doesn't work and I still have 5 elements.
When I debug it in Chrome with console.log I see an array of six objects, but when I open the array I see five elements (see pic below). What does this mean?
You're inserting a new object into that array -> newObj
For example, if you run this in Chrome console, works fine :
function aHandler (){
var a = [{1:1},{1:2},{1:3},{1:4},{1:5}];
a.splice(3,0,{1:20});
console.log(a);
}; aHandler();
Even if you insert null or undefined console.log should show you the right object.
So, maybe you modify the object somewhere between splice and console.log

Array containing objects has wrong length

I have an array like:
errors = [ {...}, {...}, {...} ]
It's an instanceof array, yet it only returns 1 for .length?
Relevant code:
if(data.error){
errors.push({'element':ele,error:data.error});
}
//Above is looped a few times and there are N number of errors now inside
console.log(errors) //Returns 2+ objects like {...}, {...}
console.log(errors.length) //Returns 1
For Uzi and Muirbot, here's the errors array:
[
Object
element: b.fn.b.init[1]
error: "You must enter "example" into the field to pass"
__proto__: Object
,
Object
element: b.fn.b.init[1]
error: "Crap!"
__proto__: Object
It is correct, this code:
var errors = new Array();
errors.push({'element':'ele', error:'data.error'});
...adds ONE object to the array. The object has two properties.
It's possible your code is executing in an order other than what you're expecting. ie, when you log both errors and errors.length, errors does contain only 1 object. But after that you are adding to the errors array, and only after that are you looking at the console. At that point you could see a larger array in errors for two reasons - first, your actual code isn't logging errors but some object that contains errors. In that case the console display is live, and will show you not what was in errors at the time, but what is in it now. Alternatively, the console could just be taking some time to log errors.
Without more code I can't be sure if this is the case. But you could verify it by replacing console.log(errors); with console.log(errors[1]);. If errors is really only 1 long at the time, it will log undefined.
The problem was that Chrome's Web Inspector's console.log is an async event. So, the length was a property lookup so it gave that back instantly, but the object with two items inside was held off until the rest of the events had fired.
In the future I, and others with this issue, should use debugger; instead.
is it an Array object or something that resembles it?
arrays do work:
> a = [{a:1}, {b:2}]
[Object, Object]
> a.length
2
you'll have to provide more code.
and now that you've provided the relevant code, the correct answer is what Steve Wellens said (which was downvoted, by the way).
Array.push adds a single element, objects may have more than one key but they're still a single object so your real case was different from your original example, which of course works.
another possibility:
> a = []
[]
> a.length = 2
2
> a
[]
> a.length
2
> a instanceof Array
true

Categories

Resources