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

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:

Related

Grabbing names of object of out a JSON object in javascript and storing it in an String Array

So the issues that I am currently having is a string manipulation logic issue. My goal is to store the names of JSON objects in a string array. So it will be easier to access the data later on. But the current issue that I am running into is that the output is nothing that I want or understand of how it is getting it. Currently I am looking for the quotes between the object names and returning it to a string using str.substring, and storing it in an index of newArr. The output equals in 4th code snippet. I have also tried putting an underscore before and after the object name in the JSON object, then searching for the underscore. From my testing this will only work with the first name, which will return "foo" in index 0, while the rest of the indexes equal to '"_'. I know there is something wrong with my logic in the function, but I can not pinpoint what it is. Any help would be appreciated
This is the function that is being ran.
exports.jsonObjectToArray = function (objectToTurn){
var oldArr = JSON.stringify(objectToTurn).split(","),
firstIndex,
secondIndex,
newArr = [];
for(let i = 0; i < oldArr.length; i ++){
firstIndex = oldArr[i].indexOf("\"");
secondIndex = oldArr[i].indexOf(firstIndex, "\"");
newArr[i] = oldArr[i].substring(firstIndex, secondIndex);
}
return newArr;
}
When the function is ran oldArr will equal to this value.
[ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
And my goal is to return this. Which will be stored in newArr.
[
"foo",
"bar",
"Mar",
"Car"
]
But after the function runs this is what I get returned.
[
'{"',
'bar":"0',
'Mar":"0',
'Car":"0'
]
To get the keys from an object, simply use Object.keys().
Quick example:
var obj = {
foo: '1',
bar: '2',
car: '3'
};
console.log(Object.keys(obj)); // ==> (3) ["foo", "bar", "car"]
let arr = [ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
let arr1 = arr.map(el => el.split('"')[1])

js array to json but some value disappear

window.onload = function() {
var arr = new Array;
var jsonObj = {
"123": "234"
};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));
}
The above code result is :
[{"123":"234"},{"123":"234"}]
I don't know why the arr['v'] disappeared?
Object and Array are not parsed to JSON the same way.
an Array will only include the numeric keys, and an Object will include all of its keys:
var Arr = [], Obj ={};
Arr[0] = Obj[0] = 'a';
Arr[1] = Obj[2] = 'b';
Arr['key'] = Obj['key'] = 'c';
console.log(JSON.stringify(Arr));
console.log(JSON.stringify(Obj));
so in your case, you could simply use an Onject instead of an array:
var arr = new Object;
var jsonObj = {"123":"234"};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));
Actually, JSON.stringify will ignore non-numeric keys in Array during the Array JSON serialization. From the latest ECMA Spec, in section "24.3.2.4 Runtime Semantics: SerializeJSONArray ( value )", we know JSON.stringify only utilizes length of Array and related numeric keys to do the serialization, and Array length will not be affected by its non-numeric keys. So it is now clear why 'v' (non-numeric keys) disappear in your final result.
You can't use a string as an array index, unless it is a string representation of an integer.
Therefore, arr['v'] has no meaning.
This stackoverflow question goes into more detail, but the relevant part:
Yes, technically array-indexes are strings, but as Flanagan elegantly
put it in his 'Definitive guide':
"It is helpful to clearly distinguish an array index from an object
property name. All indexes are property names, but only property names
that are integers between 0 and 232-1 are indexes."
In JavaScript, basically two types of array, Standard array and associative array. Standard array is defined by [], so 0 based type indexes. And in associative array is defined by {}, in this case you can define string as keys. So in your code you are using both is single array, that's not acceptable. So define the another array if you want strings keys.

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

javascript datastructure question

I have an array:
myArray = [];
To which I am adding objects:
data = [];
myArray.push( {
elem1: ...,
elem2: data.push(...);
} );
So, elem2 in the object contains an array. How can I, given myArray add new elements to the array in elem2? I tried the following:
myArray[idx].elem2.push("new data");
But got an error saying that elem2.push() is not a method.
The issue line is:
elem2: data.push(...)
data is an array. The push method for arrays does not return the array, it returns the length of the array once the item has been added.
So if you have:
var data = [];
var moreData = data.push(1);
moreData will actually equal 1.
Since the value of elem2 is actually an integer, you are then calling push on that integer. That's where you are getting the error.
The .push() function does not return the array, so that line that tries to set "elem2", well it isn't doing that.
I tried the same and works, look the code:
var a = [];
a.push({
a: []
});
a[0].a.push("a");
alert(a[0].a[0]); // return 'a'
in your array you must add another array, not the array.push(), because it will return the position that elements was inserted.

Categories

Resources