I'm storing a bunch of values in localStorage. An array with JSON objects in it to be specific.
When I want to add another object to that array here is how I pull it, parse it, push onto the array and set it again.
var clickedItem = sessionStorage.getItem('location'),
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
Later on if I pull the array and loop through the array my properties are undefined.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
}
PS. The JSON object looks completely normal when I console it. Any ideas why the props would be undefined?
UPDATE:
data is in fact an array and looping through it does give me each value from within it. However each JSON object in the array is no longer an object and must be JSON.parsed to "recreate" an object out of the string that it is.
This was a really great lesson on storing JSON objects within an array in localStorage.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
var obj = JSON.parse(data[i]); // parse it instead
console.log(obj.title); // use it as an object now
}
My assumption is that you are trying to stringify a complex object, probably something like a DOM object or another built-in API's object. What happens is that JSON.stringify will strip the object out of all methods, and this includes internal setters and getters, and you remain with an empty (or almost empty) object.
My solution in such cases is to parse the complex object into a simple one containing only the properties you need in the formatting of your choosing.
JSON.parse() returns an object but you're treating it as an array. Instead of pushing to the array, add a new item to the object.
localStorage only supports strings. Use JSON.stringify() and JSON.parse().
//demo value
var clickedItem = {"testValue":111};
var interests = [{'a':1},{'b':2},{'c':4}];
localStorage.setItem('interests', JSON.stringify(interests));
//demo value end
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
console.log(interestsParsed);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i]);
}
I think you did't stringify value of interests,(before getting value at line no.3)
Related
Why is the logged Array always filled with data? Shouldnt it be an array with only one then two then three arrays in it?
var theArray=[];
function insertValues(species,quantity){
var w = window;
w[species]= [];
for(let i =0; i<quantity;i++){
w[species].push({
species:species,
randomValue:Math.random()*10
})
// console.log(theArray);
}
theArray.push(w[species]);
}
var listOfSpecies =[{animal:"Fish",amount:5},{animal:"Shark",amount:5},{animal:"Algae",amount:5}];
for(let i = 0; i<listOfSpecies.length; i++){
console.log(theArray);
insertValues(listOfSpecies[i].animal,listOfSpecies[i].amount);
}
Woah! Firstly, don't assign to window! (unexpected things will almost definitely occur).
Also, JavaScript objects (yes an array is an object, typeof [] === "object" // true) are passed by reference, not by value.
When you add to theArray, a new reference is created. When you go to log it to the console, it shows an empty array at first, but it has actually logged a reference to theArray, therefore, when you go to inspect the contents, it shows an array filled with values;
Even try the example below, the same thing occurs (albeit much simpler to follow)
var arr = [];
for (var idx = 0; idx < 3; idx++) {
console.log(arr);
arr[idx] = idx;
}
to prevent this, you would need to copy the array, like so:
var newArray = Object.assign([], theArray);
Object.assign copies the values of the array (or object), returning a new array (again, or object), but does not create a reference back to the original array or object.
I am storing a json object in json array and assign it to another main json object, but when I print the value of main json object it display 1. Below is the code.
var jsonMainObject= {};
var jsonArray= [];
for(var j=0;j<cu.receivedData.length;j++) {
jsonMainObject["company"] = jsonArray.push(cu.receivedData[j].company);
}
console.log(jsonMainObject)
Below is the output
{ company: 1 }
But it should show the array. when i print jsonArray it shows the array of object, but when I console the output of jsonMainObject it displays the above output.
The push method returns the new length of the array. See documentation. I guess you should use:
jsonMainObject["company"].push(valueToPush)
or use concat (documentation)
jsonMainObject["company"] = jsonMainObject["company"].concat(valueToConcat)
There is no JSON at all here. JSON is a text format for representing data. What you have is a JavaScript object with a JavaScript array.
You are trying to put the array in the object at the same time as putting items in the array. The push method doesn't return the array that it was called on, it returns the length of the array. The company property will end up containing the length of the receivedData array.
You can put the array in the object from start:
var arr = [];
var mainObject = { company: arr };
for(var j = 0; j < cu.receivedData.length; j++) {
arr.push(cu.receivedData[j].company);
}
console.log(mainObject);
I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/
I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;
I have a Json like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"}}.
So ideally i should get length as 1 considering i have only 1 value on 0th location.
what if i have a JSON like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}
I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above
Any suggestions?
Objects don't have a .length property...not in the way you're thinking (it's undefined), it's Arrays that have that, to get a length, you need to count the keys, for example:
var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;
Or, alternatively, use the keys collection available on most browsers:
var length = obj.keys.length;
MDN provides an implementation for browsers that don't already have .keys:
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:
[{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}]
Then you can use .length like you want, and still access the members by index.
let _json = '{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}';
let your_json = $.parseJSON(_json);
const size = Object.keys(your_json).length;