Look for item value in localstroge - javascript

I have a $localstroge with the below stored value:
{"EmployerDetails":{"Distance":30,"EmpLatitude":51.3353899,"EmpLongitude":-0.742856,"EmpNo":39424,"Insitution":null,"PlaceName":"Camberley","TalentPoolLicences":[{"Membership":[{"Identity":39424,"Name":"Weydon Secondary School"}],"TalentPoolType":1},{"Membership":[{"Identity":2,"Name":"North East Hampshire"},{"Identity":4,"Name":"Surrey"},{"Identity":8,"Name":"Surrey"}],"TalentPoolType":3}]},"FacetFilters":{"LastActivity":0,"LocationFilterType":1,"fullorparttime_pex":null,"religion":null,"soughtphase_swk":null,"soughtrole_swk":null,"soughtsubject_swk":null},"LookingFor":null,"OrderBy":null,"PageIndex":1,"PageSize":40}
How can I get the Identity value out from it that sits inside EmployerDetails. I have tried below but it never gets inside if condition:
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.getItem(localStorage.key(i)) === 'EmployerDetails')
{ console.log('hello'); }
}
Any help on this please?

As you're searching for nested key first you need to grab the object and also need to parse it to JSON with JSON.parse then you can proceed as we do in case on normal javascript object
localStorage.getItem('signup-prefs')
This gives me a string containing my object
""name":"google","oauth_version":"2.0","oauth_server":"https://accounts.google.com/o/oauth2/auth","openid":"","username":""}"
After parsing it we can get the object and now we can find the desired property.
JSON.parse(localStorage.getItem('signup-prefs'))
Object {name: "google", oauth_version: "2.0", oauth_server: "https://accounts.google.com/o/oauth2/auth", openid: "", username: ""}
Coming to your problem
Let's say your employee information is like this i am not showing all the fields here.
var empData = {"EmployerDetails":Distance":30,"EmpLatitude":51.33538}}
Then you set the key like this
localstorage.setItem('empData', JSON.stringify(empData))
Now get the string object by key parse it to Json and find the desired key from the object loop over it to get the result.I haven't tested it but i am confident it will work. Let me know if not.
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.key(i) === 'empData') {
// Parse the string to json
var empData = JSON.parse(localStorage.getItem('empData'));
// get all the keys
var keys = Object.keys(empData);
for (var idx = 0; idx < keys.length; idx++) {
// find the desired key here
if (keys[idx] == 'EmployeeDetails') {
var empDetails = empData[keys[idx]]
}
}
}
}
One important thing about your code is
this statement localStorage.key(i)) === 'EmployerDetails' returns either true or false and writing like this
if(localStorage.getItem(localStorage.key(i)) === 'EmployerDetails') will never was executed because you didn't have any key with that name(In practice we should never use keyword as key) .

Did you try to convert it to the json object and then gets the values out?

Related

Loop through keys in JSON array that start with specific key name

Is there an efficient way to loop through the keys in a JSON array that start with the key name 'option' and either loop through them all or set a max?
I'm currently doing this following:
$.each(shopifyProductJSON.variants, function(index, variant) {
variantOptions = new Array();
variantOptions.push(variant.option1);
variantOptions.push(variant.option2);
variantOptions.push(variant.option3);
});
Which is fine but want it to be more dynamic in case more options are added in the future.
An example of part of the JSON array for each variant:
inventory_management: null
inventory_policy: "deny"
inventory_quantity: 0
old_inventory_quantity: 0
option1: "Bronze"
option2: "Satin Gold"
option3: "600mm"
position: 1
price: "550.00"
I thought this would've worked...
variantOptions = new Array();
for (i = 1; i < 4; i++) {
var key = 'option' + i;
variantOptions.push(key);
}
To solve your immediate issue you need to access the objects properties in the loop, not push the string in to the array:
let variantOptions = [];
for (i = 1; i < 4; i++) {
var key = 'option' + i;
if (data.hasOwnProperty(key)) {
variantOptions.push(data[key]);
}
}
That being said, if the options are going to be of a dynamic length it makes far more sense to return them as an array instead of individual numbered properties, assuming you have control over the response format.
You could change the response to this:
{
inventory_management: null
inventory_policy: "deny"
inventory_quantity: 0
old_inventory_quantity: 0
options: ['Bronze', 'Satin Gold', '600mm'],
position: 1
price: "550.00"
}
Then the JS to access the options becomes a simple property accessor:
let variantOptions = data.options;

Updating the value of an object inside a loop using javascript

I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.

JS code returning error

I'm new to JS and i had to use it for Cloud Code Parse feature. I have a class called "user_picture", through the code i query all the objects and go through it's "City" attribute. i want the response to be an array of unique city names. Anyway, here is the code i'm working on:
Parse.Cloud.define("cities", function(request, response) {
var query = new Parse.Query("user_picture");
query.find({
success: function(results) {
var cities = new Array();
for (var object in results){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
response.success (cities);
}, error: function() {
response.error("Error");
}
});});
However, when i run this function i receive the following error:
Error: TypeError: Object 0 has no method 'get'
at query.find.success (main.js:15:30)
at Parse.js:2:5786
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at r (Parse.js:2:5117)
at Parse.js:2:4531
at Array.forEach (native) (Code: 141, Version: 1.2.18)
And the response returns null. I tried printing one object from the results array in order to make sure i'm receiving the right query, and it's printing fine the city. What could be the problem?
The for in loop iterates through all the keys of an object literal. Since results is an Array it will iterate through the keys of the Array, which are '0', '1' etc.
This means that the object variable will hold those key vales. And since they are not objects they don't have a method called get.
You need a forEach loop instead.
results.forEach(function(object){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
});
Or if you're targeting ES3 then you should use a for loop
for(var i = 0, length = results.length; i< length; i++){
var object = results[i];
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
I recall working with Parse objects a bit and there seemed to be times to access them as an object (by direct parameter access) and sometimes by using the get method and it looks like you're mixing up the array access and object (from Parse) access methods.
Also, your list generator doesn't seem like it's really building a unique list. You only check to see if the current city is the same as the city you're going to add.
I might do something more like this (for the success method):
function(parseResults) {
var cities = {};
var ii=0;
var nResults = parseResults.length
for(;ii<nResults;++ii) {
cities[result.get('city')] = 1
}
var citiesArray = cities.keys();
response.success(citiesArray);
}
What we do here is build up an object whose keys are city names. Then return the keys as an array. What this does for us is automatically build a unique list because object keys should be unique.
If the result.get gives you problems, try replacing it with result.city. But i suspect the error you were seeing with your first example was trying to call get on the Array element.

won't loop array javascript

Why cant i access my array?
function map(array){
for(i=0; i <=array.length; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].from_user;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
It gives me undefined for every element.I want to access it and pass the variables to the geocode function.
data structure:
array=[{user: a,user_id: b,date: c,profile_img: d,text: e,contentString: f,url:
g,location:o},{user: a,user_id: b,date: c,profile_img: d,text: e,contentString:
f,url:g,location:o},{user: a,user_id: b,date: c,profile_img: d,text:
e,contentString: f,url: g,location:s}];
dont worry about the values..!
I forgot to mention when i first made the post(question). the location of the array is inserted in the previous function whereas the array didn't include the attribute location from previous functions
When calling the function, use the object literal construct enclosed in an array literal, otherwise all values will be returned as undefined. This is how you should call your function:
map([{ // array literal enclosing an object literal
location : 1,
from_user : 2,
created_at : 3,
profile_img: 4,
text : 5
}]);
Moreover, in your loop, change:
for (i = 0; i <= array.length; i++ ) ...
...to
for (var i = 0; i < array.length; i++) ...
If you have a pre-defined array, name it and pass it to the function like this:
map(arrayObj)
If the array you pass in has a length of 0, the way you're looping it is going to try and access the list element at 0, which is going to be undefined.
However, regardless of the contents of your array, this line will always cause you trouble:
for(i=0; i <=array.length; i++)
When check the length property of your array, it is telling you the number of elements in the array. Since arrays use 0 based indexing, you're going to overrun the bounds of your array with this loop everytime.
var myArray = [1, 2, 3];
myArrary[0]; // This is 1
myArray[2]; // This is 3
Since you are looping between 0 and the length of the array, which happens to be 3, the last element you attempt to access will no exist.
myArray[3]; // Undefined
You need to check i < array.length rather than i <= array.length.
Your code is fine. With the provided input and function you get this:
loco
userundefined
loco
userundefined
locs
userundefined
The reason every user is coming up as undefined is because of:
var user = array[i].from_user;
console.log("user"+user);
The objects you are passing in do not have a from_user property, so naturally it comes up as undefined. Maybe you meant array[i].user_id?
Also, as Aesthete pointed out, you're running outside the bounds of your array because of the way you're checking for length. Do this instead:
for(var i = 0, n = array.length; i < n; i++) {
// your code in here
}
Notice that I preface i with var so it does not become an implicit global. Also, I declare a second variable n so that you only need to access array.length once. This is common practice.
So, putting it all together:
function map(array){
for(var i = 0, n = array.length; i < n; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].user_id;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
array=[{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString: 'f',url:
'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString:
'f',url:'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text:
'e',contentString: 'f',url: 'g',location:'s'}];
map(array);
Notice I changed your object properties to strings - this is because you did not give values for these, but you probably don't want to do this. Output is:
loco
userb
loco
userb
locs
userb
All is well. If you are still getting undefined for location then your error must lie with the o property of the objects you're passing in.

remove json attribute where attribute is a variable

I have a news feed where items in the feed are created from JSON returned from a server. When the user takes an action on an item, I want to remove it from the object via javascript.
The feed looks like this:
{"newsFeed":[{"feedId":"1",
"title":"item1 title",
"desc":"description of the item"},
{"feedId":"2",
"title":"item2 title",
"desc":"description of the item"}]}
I'm trying to remove a JSON attribute or entry where the feedId is passed in via a variable using jQuery. I'm not sure exactly where I'm going wrong here, but when I alert the feed before and after the removal of the object, I'm getting the same response:
function removeFromFeed(feedId){
var newsFeed=jQuery('div#newsFeed').data('newsFeed');
alert(newsFeed.toSource());
delete newsFeed.feedId[feedId]
jQuery('div#newsFeed').data('newsFeed',newsFeed);
alert(newsFeed.toSource());
}
If I undertand you correctly you want to remove e.g. this whole entry {"feedId":"1", "title":"item1 title", "desc":"description of the item"} if removeFromFeed(1) is called.
So what we need to do is remove an entry from an array.
New version which should work now. (btw. what is this toSource() my browser doesn't know this method)
//http://ejohn.org/blog/javascript-array-remove/
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
function removeFromFeed(feedId){
var data = jQuery('div#newsFeed').data('newsFeed');
var len = data.newsFeed.length;
for (var i = 0; i < len; i++) {
if (data.newsFeed[i].feedId == feedId) {
data.newsFeed.remove(i);
break;
}
}
jQuery('div#newsFeed').data('newsFeed', data);
}
Demo: http://jsbin.com/ekali3 (Code view: http://jsbin.com/ekali3/edit)
I'm not sure why the 'Array.prototype.remove' stuff was breaking my page, but I created a new array and just left out the object I wanted to remove.
var newsFeed=jQuery('div#newsFeed').data('newsFeed');
var newFeed={"feed":[]};
alert(newsFeed.toSource());
for (var i = 0; i < newsFeed.length; i++) {
if(newsFeed.feed[f].shiftId!=shiftId){
newFeed.feed.push(newsFeed.feed[f]);
}
}
seems to work.

Categories

Resources