Print array with objects in javascript - javascript

i have this array
"[{\"category_id\":\"2\",\"category_name\":\"Fun\"},
{\"category_id\":\"3\",\"category_name\":\"Science\"},
{\"category_id\":\"4\",\"category_name\":\"Art\"},
{\"category_id\":\"5\",\"category_name\":\"Nature\"},...]"
i want to output this in user readable format

It’s not an array. It’s a string.
Perhaps you mean
var x = "[{\"category_id\":\"2\",\"category_name\":\"Fun\"},{\"category_id\":\"3\",\"category_name\":\"Science\"},{\"category_id\":\"4\",\"category_name\":\"Art\"},{\"category_id\":\"5\",\"category_name\":\"Nature\"}]"
console.log(JSON.stringify(JSON.parse(x)))

Try below code.
var obj = "[{\"category_id\":\"2\",\"category_name\":\"Fun\"},{\"category_id\":\"3\",\"category_name\":\"Science\"},{\"category_id\":\"4\",\"category_name\":\"Art\"},{\"category_id\":\"5\",\"category_name\":\"Nature\"},...]";
obj = obj.replace(/\\/g, '');
console.log(obj);

Related

Why does JSON.stringify() not work on this array?

I have an array which is declared like this:
array = [];
and has values as shown below -
....
ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc"
ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4"
....
These values are printed when I do console.log(array);
When I try to do a JSON.stringify(array), it does not seem to work. I want to store this array in localStorage using localStorage.setItem().
I tried an example like in this in the browser console:
var arr=[]
arr[0] = 1
arr[1] = 2
JSON.stringify(arr);
And the above example worked perfectly fine.
Please provide your inputs, I have been stuck at this for hours.
You are trying to assign values in array like objects ; index can only be o,1,2 etc. not the strings like you have used. If you must do this, create an array of objects
the problem is that you are trying to set the array index as strings 'ChIJOaegwbTHwoARg7zN_9nq5Uc' and 'ChIJXTwCdefHwoAR9Jr4-le12q4' and although the browser seems to print it in the console, but array considers only integer keys as valid indices, so if you try to print array.length, it will print 0 and hence operations such as JSON.stringify(array) don't return you anything
var array = [];
array['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
array['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(array);
console.log(array.length)
What you need is not an array but an object
var obj = {};
obj['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
obj['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(obj);
console.log(JSON.stringify(obj))
That's not an array, but an object. Objects don't stringify as well as arrays do.
Basically:
String = 'This is a string'
Array = [
'This is a string',
'And so is this'
]
Object = {
firstString : 'This is a string',
secondString : 'And so is this.'
}
This works for me in a plunker.
let array = [];
array.push({"ChIJOaegwbTHwoARg7zN_9nq5Uc":"ChIJOaegwbTHwoARg7zN_9nq5Uc"});
array.push({"ChIJXTwCdefHwoAR9Jr4-le12q4":"ChIJXTwCdefHwoAR9Jr4-le12q4"});
console.log(JSON.stringify(array));
If you do a console.log(array), you should see something like this:

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

Storing key values array in localstorage

I am trying to store array in localstorage with following code :
var tempval = [];
tempval['key'] = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
but in localstorage it showing only []
So how to store it and where I am doing mistake ?
Here is your code:-
var tempval ={};
tempval.key = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
So Your Question is not that much clear to me but i am trying to give you a general solution for storing multidimensional array in local storage ,
var a= [[1,2,3],["hello","world"]]; // multi dimentional array
console.log(a);
var b = JSON.stringify(a); // converting the array into a string
console.log(b);
localStorage.setItem("TestData",b); // storing the string in localstorage
var c= JSON.parse(localStorage.getItem("TestData")); //accessing the data from localstorgae.
console.log(c);
Here is the code running in Jsbin
JavaScript does not support arrays with named indexes.Arrays always use numbered indexes in javascript. Use object if you wanna use named index.
Using array (numbered index)
var tempval = [];
tempval[0] = 1;
Using object (named index)
var tempval = {};
tempval['key'] = 1;
Use var tempval ={}; instead of var tempval = [];
This question has been answer already (duplicate of):
https://stackoverflow.com/a/3357615/10387837
The short answer is localStorage.setItem only supports strings as arguments. In order to use it with arrays its recommended to use JSON.stringify() to pass the parameter and JSON.parse() to get the array.

Convert array to Object by JSON.parse

var arr=[];
arr['first']='val1';
arr['second']='val2';
var json=JSON.stringify(arr);
var obj=JSON.parse(json); //obj is array
Can I return object {"first":"val1","second":"val2"} ?
P.S.: I read Convert Array to Object topic
I'm interested in this way of the function
If somebody has abused arrays like that, JSON does not help you. It will only serialize the numeric indices of Array objects, nothing else. Copy the properties by hand:
var obj = {};
for (var prop in arr)
if (arr.hasOwnProperty(prop)) // don't copy enumerables from Array.prototype
obj[prop] = arr[prop];
console.log(obj); // {"first":"val1","second":"val2"}
You shouldn't use an array to represent this:
Do this instead:
var obj = {first:"val1",second:"val2"};
Just define the object directly . Stringify and parsing is not necessary

JavaScript Variable Declaration

This is a really stupid question, but I'm just drawing a blank here...
What type of variable declaration is this:
var s1 = [1,2,3,4]
Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.
var s1 = [];
for(x in data[i].uh) {
s1 += data[i].uh[x];
}
var s1 = [1,2,3,4]
is an array declaration of four integers using "Array Literal Notation"
You don't need a loop to copy the array, simply do this:
var s1 = data.slice(0);
or in your example you might want this:
var s1 = data[i].uh.slice(0);
Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
"The slice(0) method means, return a
slice of the array from element 0 to
the end. In other words, the entire
array. Voila, a copy of the array."
That is called an Array, which can be declared with new Array() or by using the array literal [] as in your example. You can use the Array.push() method (see docs) to add a new value to it:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
This
var s1 = [1,2,3,4]
is an array declaration.
To add an element to an array, use the push method:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
s1 is an array, it's a proper Javascript object with functions.
var s1 = [];
is the recommend way to create an array. As opposed to:
var s1 = new Array();
(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)
To add items to an array use s1.push(item) so your code would be:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.
It's declaring a local variable with an Array with 4 members.
If you want to append to an Array, use the push() method.
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);

Categories

Resources