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.
Related
I have a big array, it has many element,
I need to display it in console,
I use console.log() but only a part of it was displayed.
How to display full content?
Run it through JSON.stringify so you are logging a single string and not a complex data structure.
You can use
console.dir(myArry, {'maxArrayLength': null});
The console method log() displays the toString representation of any object passed to it. The Console method dir() displays an interactive list of the properties of the specified JavaScript object
Link for reference : Dumping whole array: console.log and console.dir output "... NUM more items]"
as say here How can I get the full object in Node.js's console.log(), rather than '[Object]'?
you can convert your element (object or array) directly in json by using
console.log('my elem : %j', myObject);
or if you want more display option, you can use util.inspect
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
For larger arrays, this works nicely:
myLargeArray.forEach( element => console.log( JSON.stringify( element ) ) );
So, I have a similar situation as with this question which "SHOULD" work but doesn't
How can I access and process nested objects, arrays or JSON?
My JSON is basically this... reduced for brevity.
NOTE:
"{"message": [{"id":"1","element1":"Something","element1":"Something"},{"id":"2","element1":"Something","element1":"Something"}],"status": "success"}"
What happens is that if I select response coming from the API, I get the entire JSON.
If I type: response.message, I get UNDEFINED. That makes absolutely no sense.
This is what it looks like in sessionStorage:
I just want to do what I've always done: response.message or response.whatever to just give me what's "INSIDE" message and for some reason, no matter what I do, it's not working.
Here's the part of the code where I get the response with message
globalService.commonService('getData', reqPkg).then((response) => {
$scope.theReport.data = JSON.parse(response);
});
if I do this I get undefined
$scope.theReport.data = JSON.parse(response.message);
I've tried JSON.stringify too, same result.
This is from a previous question which works fine and is in deed just the Objects from the Array of Objects.
const arrResult = Object.keys(objCount).map(k => ({'name': k, 'displayName': k, 'count': objCount[k] }));
$scope.theReport.data = JSON.parse(response).message; to get all entries from message into $scope.theReport.data.
Your response is a string, so parse the response and just grab the message key from that.
I need an array of objects to be passed to cavansJs. This array is an element of a more complex object passed from PHP to a JS script in this way
var active_alarms_data = JSON.parse('<?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>');
I tried also
var active_alarms_data = <?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>;
This is the structure of the main object
The data for the chart is in the sub-array factory_made_avg_graph_prices_stats, printing on console.log the whole object, this field appears to be properly formatted as an array; it can be seen that is declared as an Array type with 104 elements each of which is indexed with a number from 0 to 103. Good is what I need!! But, when I refer directly to the array I got something of very strange
console.log("ELEMENT 0: " + active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);
I got
and the chart remains empty probably just because the expected data format is different than the past one. Any suggestion?
Nothing is wrong with your code.
It's just the console log that is throwing you off. Accessing each of the elements as you are now will work fine. The reason you are seeing [object Object] is because when you concatenate (join with '+') something to a string in javascript, if it isn't a string, it will try to convert it to a string first.
You are looking at a string representation of each object in the array. If you remove the "ELEMENT 0:" and only log the array, then you'll see what you saw first. here's an example:
const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0: ' + obj.test)
console.log(obj.test)
Or, if you really needed to see "Element 0", you can use a comma, rather than direct concatenation:
const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0:', obj.test)
Console like this :
console.log("ELEMENT 0: " ,
active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);
Replace '+' to ',' in console
What is the problem here?
First example:
console.log(ntags);
console.log(JSON.stringify(ntags));
Console output (Google Chrome):
[Array[0], Array[0]]
0: Array[0]
length: 0
numerical_value: null
tag_id: "3"
1: Array[0]
length: 0
numerical_value: "12"
tag_id: "5"
[[],[]]
Obviously the variable "ntags" is populated with a certain number of associative arrays which have certain values. However JSON.stringify makes an empty array.
Second example - the same problem occures if I try to post the variable ntags with Ajax directly:
$.ajax({ type:"POST", url: "/?tag_connection=update&fdata_id="+save_id, data: {cons: ntags}, success: function(result){
...
});
The client does not send any post data to the server side ($_POST empty in PHP).
JSON serialising does not serialise properties of an Array, this is simply not the expected behaviour - an array is a list of values, in order. The properties for this do not get serialised simply because it is not expected behaviour. You could technically serialise this, but it would defeat the point of having an Array as a data type.
For example, let's say we serialise the array [1,2,3,4] - then the expected output in JSON is:
[1,2,3,4]
simply because of it's type. If arrays were serialised like objects, the output might look something like this:
{0:1,1:2,2:3,4:4,length:4}
As you can see this is much longer - which means more data you need to send over a network, and a custom object to be created in any other programming language. This way we all agree on arrays.
So in this instance, you might just want to use an object, which will output the expected value. Try serialising this:
[{length:0,numerical_value: null, tag_id: 3}, {length: 0, numerical_value: null, tag_id:2}]
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