get the value of an object key value that was stringify - javascript

I save some items in localstorage and stringify the key value before storing it.
localStorage.setItem(this.set_name, JSON.stringify(this.description))
That gives me key:
item1 Value: [{"description": "some description that was store"}, {"description": "some description that was store"}]
When i get the key value with JSON.parse it returns as an Object Object as expected, So without doing the JSON.parse it will return the whole value as is.
What I want to do is to return what's inside the description only, the "some description that was store" and not the whole value.
How would I do it?
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
console.log(JSON.parse(itemDesc))
}
}
Console gives me '(3) [{…}, {…}, {…}]'

You should parse it first, and then fetch it from the array.
Considering that var stringy is the data you got from your localstorage, replace it with localStorage.getItem(<your key>);
var stringy = "[{\"description\": \"some description that was store 1\"}, {\"description\": \"some description that was store 2\"}]"
var parsedArray = JSON.parse(stringy);
for(var i = 0; i < parsedArray.length; i++){
document.getElementById('area').innerHTML += '<p>'+parsedArray[i].description+'</p>';
}
<div id="area"></div>

In general i would create separate service like
storage it should make stringify on save and JSON.parse on get
also it should have inner cache object - parsed object or undefined if object is not in cache and should be extracted and parsed from localStorage
if you are aware about performance, and you can't use JSON.parse due to too large object or similar, i would try to save descriptions in separate key-value pair
like
localStorage.setItem(this.set_name, JSON.stringify(this.description));
localStorage.setItem(this.set_name+'_'+this.descriptionKey,JSON.stringify(this.description))
to have possibility to retrieve description only by descriptionKey without parsing all object

I tried to understand you problem, but m not sure if i did, still assuming, you are saving whole List/Array as an one item in single LocalStorageItem, you will have multiple descriptions in one item, so there are multiple arrays, and each array having multiple objects hence multiple descriptions, heres my solution for this problem, if you explain more i will edit the same.
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
var oneLocalStorageItem = JSON.parse(itemDesc);
oneLocalStorageItem.map(function(oneObjectItem){
console.log(oneObjectItem.description);
})
}
}

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

JSON Object of Arrays

I'm pulling my hair now with this. I have this str variable in parent window after getting from child window with JSON.stringify. The group of arrays are a collection of inputs.
var str = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
What I did was
for(var i in str) {
console.log(i);
console.log(JSON.parse(str[i]));
}
//the output example:
SHOP1
[["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]]
But it will never detect [["name1",1,"anotherdata1"],["name2",2,"anotherdata2"]] as an array but as string.
Is there any way to make Javascript to detect it as an array? Or is there better suggestion or alternative to this?
The trick is to parse it twice. First to get the string, then second to convert it to the arrays.
var obj = {"SHOP1":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\"",
"SHOP2":"\"[[\\\"name1\\\",1,\\\"anotherdata1\\\"],[\\\"name2\\\",2,\\\"anotherdata2\\\"]]\""};
for (var shopname in obj) {
var shop = obj[shopname];
shop = JSON.parse(JSON.parse(shop));
console.log(shop);
console.log(shop.length);
}

Json Object push not working using AngularJS

I have a data with certain rule. I want to create a json object to manage the rule. There is problem to create a json object as my need. Here my array data.
$scope.data = ["Crust^Pan^Medium=NA", "Crust^Pan^Large=NA", "Crust^Thin Crust^Medium=10.50"]
I want a output like this:
{
"Pan": {
"Medium": NaN,
"Large": NaN,
},
"Thin Crust": {
"Medium": 10.50
}
}
Here my code,
$scope.crustRule = {};
for(var i=0; i<$scope.data.length; i++) {
var tempCrust = {};
var trimOne = $scope.data[i].split('^');
var trimTwo = trimOne[2].split('=');
if(trimOne[0] == 'Crust') {
tempCrust[trimTwo[0]]=parseFloat(trimTwo[1]);
$scope.crustRule[trimOne[1]].push(tempCrust);
}
}
console.log($scope.crustRule);
You first need to create an object $scope.crustRule[trimOne[1]] before you can push objects into it. Something like
$scope.crustRule[trimOne[1]] = {};
$scope.crustRule[trimOne[1]].push(tempCrust);
the push function has to exist. you can grab it from the Array property if you want.
only do this if it has to be in an object structure
var x = {length:0,push:Array.prototype.push};
x.push("jump");
console.log(x);//Object {0: "jump", length: 1}
I go over the mininmum requirement for some array functions to work on an object:
Mimic the structure of a javascript array object
EDIT:
I noticed your reuirements are need an object without a length and string index based instead of number index based. going to test something
darn I was hoping something wild was already there and tried
var x = {};
x += {"BadGuy": "Joker"};
console.log(x)//[object Object][object Object] //:(
so I made my own push function
var x = {push:ObjPush};
x.push("jump");//Object cannot add (string) yet Coming soon
y = {"BadGuy": "Joker"};
x.push(y);
console.log(x);//{"BadGuy": "Joker"};
function ObjPush(obj)
{
if ((typeof obj).toLowerCase() == "object")
{
for (var i in obj)
{
this[i] = obj[i];
}
}
else
{
console.log("Object cannot add (" + typeof obj + ") yet\n Coming soon");
}
}
Note:
I haven't added any handling to check for same properties. so any properties with the same name will override original properties.
EDIT:
I integrated my code with yours and got a strange output unfortunately.
for some reason instead of adding medium and large as properties to the inner objects it only adds the last 1 for example i get the output
{"Pan":{"Large":null},"Thin Crust":{"Medium":10.5}}
EDIT:
OK I found where my issue was. I get the expected output now. added a check to make sure that $scope.crustRule[trimOne[1]] is only initialized if it doesnt exist yet.
if(typeof $scope.crustRule[trimOne[1]] == "undefined")
$scope.crustRule[trimOne[1]] = {push:ObjPush};

json stringify result get value on specific key

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}]
I have here a stringfy json i want to know how to get a value of all the menuname in this json object any idea appreciated
UPDATE:
I tried this one
here but I get undefined in console
UPDATE
[{"displayorder":"1","menuname":"Menu Management","menuid":"1","submenuurl":"","parentid":"1"},{"displayorder":"1","menuname":"hr sub menu","menuid":"7","submenuurl":"error.php","parentid":"2"},{"displayorder":"2","menuname":"Role Management","menuid":"2","submenuurl":"","parentid":"1"},{"displayorder":"2","menuname":"menu 2 management2","menuid":"8","submenuurl":"","parentid":"2"},{"displayorder":"3","menuname":"hrsubmenu","menuid":"3","submenuurl":"contactus.php","parentid":"2"},{"displayorder":"3","menuname":"submenuaccounting","menuid":"4","submenuurl":"imagegallery.php","parentid":"3"}];
how to get all all details in the second json with parentid depending on above menuid?
Working example:
http://jsfiddle.net/0866pay3/
var json = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
json.forEach(function(el, idx){
console.log(el.menuname);
});
Documentation Update
If you check out this article, you'll see the following:
callback is invoked with three arguments:
the element value
the element index
the array being traversed
So, idx is just a common way of representing the element index. You can call this whatever you'd like - theIndex, myRandomName, etc.
var myjson = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
var menu_names = [];
for (var x = 0 ; x < myjson.length; x++){
if(myjson[x].hasOwnProperty('menuname')){
// do something usefull here
console.log(myjson[x]['menuname']);
// add value to new array
menu_names.push(myjson[x]['menuname'])
}
}
console.log(menu_names);

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;
}

Categories