Strip # from API response with Javascript - javascript

I am working with an api that provides a response like this:
{
"statuses": {
"status": [
{
"#array": "true",
"#id": "1",
"#uri": "https://api.com/people/statuses/1",
"name": "Member",
...
]
}
}
I need to use javascript to strip the # out of the key names. Eg "#id" to "id". How can I do this?

You'll have to manually iterate and rename each key and remove the original attribute in a given status. Something like
response.statuses.status.forEach(function(status) {
var keys = Object.keys(status),
keyCount = keys.length;
for (var j = 0; j < keyCount; j++) {
var thisKey = keys[j];
status[thisKey.replace('#', '')] = status[thisKey];
delete status[thisKey];
}
});

Other than looping through the keys and building a new object like everyone else has stated, you could get really crazy and do something like this:
// convert to string, if not already a string response
var responseStr = JSON.stringify(myObj);
// REGEX AWAY THE STUFF
responseStr = reponseStr.replace(/#/g, "");
// convert to obj
myObj = JSON.parse(responseStr);
Although, if any of your data has # in it naturally, it would get regex'ed out. I know, It's crazy. Thought it might be worth mentioning.

You can't just rename the keys within javascript objects, but you could always extend the response object. Something like this would work:
for(var i = 0; i < statuses.status.length; i++){
var status = statuses.status[i];
status.array = status["#array"];
status.id = status["#id"];
status.uri = status["#uri];
// could also delete properties here... see below...
}
That would give you what you were looking for, although all the properties with '#' would still exist. You could take it a step further and delete those properties, though.
delete status["#array"];
delete status["#id"];
delete status["#uri"];
I hope that's what you're looking for. Let me know if that helps!

function stripSymbol(obj) {
var type = Object.prototype.toString.call(obj);
if (type === '[object Array]') {
for (var i = 0, len = obj.length; i < len; i++) {
stripSymbol(obj[i]);
}
} else if (type == '[object Object]') {
Object.keys(obj).forEach(function(key) {
if (key[0] === '#') {
var newKey = key.substr(1);
obj[newKey] = obj[key];
delete key;
key = newKey;
}
stripSymbol(obj[key]);
});
}
}
stripSymbol(data);
This will recursively crawl through and object and remove the '#' at the beginning of any keys.

well first of all array is probably a reserved word for any javascript parser but ignoring that try this...
statuses.status[0].array = statuses.status[0]["#array"];
delete statuses.status[0]["#array"];
the reason you need to do this is because javascript doesn't support renaming keys.

Related

Output several cells from inner loop

this is my code:
start() {
let columns = ['A'...'Z'];
let fields = {
id: [
'Medlemsnummer',
],
name: [
'Namn',
],
};
let out = {};
let self = this;
columns.forEach(function(column) {
for(let row = 1; row < 101; row++) {
let cell = column + row;
let d_cell = self.worksheet[cell];
let val_cell = (d_cell ? d_cell.v : ' ');
let cell_string = val_cell.toString().toLowerCase();
let cellString_stripped = cell_string.replace(/(?:\r\n|\r|\n)/g, '');
for (var key in fields) {
// skip loop if the property is from prototype
if (!fields.hasOwnProperty(key)) continue;
var obj = fields[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if(!obj.hasOwnProperty(prop)) continue;
obj.forEach(function(term) {
if(cellString_stripped.match(new RegExp(term.toLowerCase() + ".*"))){
//out.push(obj + ': ' + cell);
//out[obj] = {cell};
out[obj] = cell;
}
});
//out[obj]
}
}
}
});
console.log(out);
},
and my problem is that i want several matched cells in out[obj] = // array of matched cells.
how can i do this in javascript?
so my out should look like this:
out = [ medlemsnummer: ['A11','A23','A45'], name: ['B11','B23'] etc... ]
please comment if you need me to explain better.
Kind regards,
Joakim
Looking at your loops, I think you got a little lost in your own structures. out[obj] = cell definitely doesn't seem right; obj is an object, it cannot be used as a key in another object. Here's my take with some notes, hope I interpreted both your code and your question correctly. I'm starting from the loop after all your variables like cell, d_cell, etc. are initialized):
for (let key in fields) {
if (!fields.hasOwnProperty(key)) continue;
let terms = fields[key];
// fields[key] yields us an array, e.g.:
// fields['id'] = [ 'Medlemnummer' ]
// so we can iterate over it directly with for..of.
// Note also: variable names like "obj" make reading your code
// difficult; use meaningful names, e.g. "terms".
for (let term of terms) {
let regex = new RegExp(term.toLowerCase() + ".*");
// Note: RegEx.test() is more efficient than String.match()
// if all you need is a yes/no answer.
if (!regex.test(cellString_stripped)) continue;
// Here's the part you actually needed help with:
if (!out[term]) {
out[term] = [];
}
out[term].push(cell);
}
}
Addendum: In the code I'm sticking with your solution to use RegExp to test the strings. However, if all you need to check is whether the string starts with the given substring, then it's much shorter and more efficient to use String.startsWith():
for (let term of terms) {
if (!cellString_stripped.startsWith(term.toLowerCase())) continue;
// Here's the part you actually needed help with:
if (!out[term]) {
out[term] = [];
}
out[term].push(cell);
}

Look for item value in localstroge

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?

checking key using 'for in' returns undefined

I'm checking to see if a key exists in an object from another object so I am doing something like this:
var user = {
'email' : 'dothis',
'derp' : 'yo'
};
And then I'm checking to see if it exists within this:
var cookies = {
'email':'hello#gmail.com'
}
I'm checking like this:
for(var key in cookies) {
if(user[key]){
// do this
}
}
But no matter what I do it will return undefined. However it does work when I just do:
user['email'];
Which is correct.
EDIT: Let me add on to exactly what I'm doing.
So I'm getting all the cookies in the browser using this function:
getAllCookies : function(){
var pairs = document.cookie.split(";");
var cookies = {};
for (var i=0; i<pairs.length; i++){
var pair = pairs[i].split("=");
cookies[pair[0]] = unescape(pair[1]);
}
return cookies;
}
From that I get the object cookies.
There are spaces in a cookie string, so you need to trim the name first, or just split with whitespace:
var pairs = document.cookie.split(/\s*;\s*/);

Separate Array into two arrays

I wonder how I can separate an array that consists of "123.152323,152.123232" into "123.152323" and "152.123232".
I pick up the string from a rest, the string looks like this.
responseHandler({"items":[{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]...
function responseHandler(json) {
var markers = new Array();
for (var i = 0; i < json.items.length; i++) {
markers[i] = (json.items[i].location);
}
}
Can I split the location before putting it into an array? I know split() exists but if the string has more information than just location, such as name, city, etc.
Why reinvent the wheel ? It seems like you have a valid json object, Why not simply use JQuery.parseJSON
Modern browser contain native JSON methods (like JSON.parse, JSON.stringify). Use those, or use an external library like this one from google. It makes your life easier (no need for splitting or regex searches and the like):
function responseHandler(json) {
// use native (JSON.parse), json-sans-eval would be: jsonParse(json)
var myJson = JSON.parse(json)
,markers = []
,i = 0
,len = myJson.length;
for (; i < len; i = i+1) {
markers.push(myJson[i].location);
}
return markers;
}
Edit after comment: you are passing a js-object, so JSON-parsing is not necessary.
function responseHandler(json) {
var markers = []
,i = 0
,len = json.length;
for (; i < len; i = i+1) {
markers.push(json.items[i].location);
}
return markers;
}
//for example
var json = {"items":[
{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]},
{"name":"yyy","location":["yy.yyyyy","yy.yyyyy"]}
]
};
var locations = responseHandler(json);
//=> now locations[0][0] is 'xx.xxxxx', locations[1][0] 'yy.yyyyy'
(May be you should try finding some reading material on the web about javascript basics)

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