JavaScript: Accessing Object [Object] from local storage in html5 - javascript

i've got this code to list all saved players in a game:
function getAllPlayers(){
for (var i = 0; i <= playerCount; i++){
object[i] = JSON.parse(localStorage.getItem("savedData"+i));
console.log(object[i]);
}
}
I get object[object], which is a collection of objects. In console, I get to see their properties and values, however with:
for (var name in object) {
alert('"' + name + '"="' + object[name] + '"');
}
I still cannot access these properties. Is there a method to get each object into a separate variable, so that I can access them via varName.property syntax?

The problem is because object is not really an object this is array of objects and you should access property of some object in this array
for (var i = 0; i < object.length; i++)
for (var name in object[i]) {
alert('"' + name + '"="' + object[i][name] + '"');
}
//currently you have to read it like this
for (var i = 0; i < object.length; i++){
var singleObj = object[i][0]; // additional 0 index
for (var name in singleObj) {
alert('"' + name + '"="' + singleObj[name] + '"');
}
}
like you are using it here
console.log(object[i]);

If your problem is that you are getting [object Object] in your alert() box:
alert(someObject) calls native Object.toString() method of an argument passed, that is why you are getting [object Object].
Use JSON.stringify(someObject) to simply convert your object to JSON string, or implement your own method to generate a string from an object.

Related

How to iterate over a json array

I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all

Accessing an object inside of an array inside of an object in javascript

I'm trying to write a function that accesses an object inside of an array inside of an object and then push that into an array.
This is the code I have right now:
Javascript
stuff: function (index1, index2) {
for (var i = 1; i < index1.length; i++) {
state[index2].push(foodData[index1][i].name);
}
}
When I run storage.stuff('ingredientsToInclude', 'desired') I get the following error:
Cannot read property 'name' of undefined
However, if I access foodData["ingredientsToInclude"][1].name in the console it returns the correct value.
Not sure the reason for the discrepancy.
you are looping over string 'ingredientsToInclude' instead of actual array foodData['ingredientsToInclude'].
So change for (var i = 1; i < index1.length; i++) { to for (var i = 1; i < foodData[index1].length; i++) {

How to return all objects in javascript array

I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}

Storing and retrieving objects in javascript array();

Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:
map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
The object I have right now looks like:
node = {};
node = {ground:0, object:1};
But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?
Do you mean:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
console.log(map[i].ground + " item " + map[i].item);
}
Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
for (var i=0, iLen=map.length; i<iLen; i++) {
alert(map[i].ground);
}
Edit
...
alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...

Write out name and value from dictionary

This is trivial I know but I'm so used to OOP languages. I'm trying to figure out how to write out each name/value in either one alert or many, just so I can verify the data
var dCookieNameValuePairs = {};
for (i = 0; i < cookieValues.length; i++)
{
var akeyValuePair = aCookieValues[i].split("=");
dCookieNameValuePairs[keyValuePair[0]] = keyValuePair[1];
}
// display each name value pair testing
for (i = 0; i < dCookieNameValuePairs.length; i++)
{
alert("Name: " + dCookieNameValuePairs[] + "Value: " +
}
I'm stuck at the second for loop...I am not sure how to iterate through the dictionary and then focus on each name/value to spit it back.
You want to use for..in for enumerating through a dictionary/map.
for ( var prop in dCookieNameValuePairs ) {
if ( dCookieNameValuePairs.hasOwnProperty( prop ) ) {
alert( dCookieNameValuePairs[prop] )
}
}
I may have typo'd. Only use .length when you are dealing with an array [] or a custom array-like object that you defined to have .length populated.
for (i in dCookieNameValuePairs) {
alert("Name: " + i + " Value: " + dCookieValuePairs[i]);
}
See the "JavaScript Does Not Support Associative Arrays" section of this page for more details.
If you don't need an associative array, you might put the keys and values into an array of objects instead. So your first loop would look something like this:
for (i = 0; i < cookieValues.length; i++) {
var akeyValuePair = cookieValues[i].split("=");
dCookieNameValuePairs.push({key: akeyValuePair[0], value: akeyValuePair[1]});
}

Categories