convert from hastable result into a string using Java Script - javascript

I have a result of type of:
EMailLabel: "Mailing address"
LogLabel: "User login"
LoginButton: "Enter the program"
And in order to manipulate this result by splinting it into pairs, I need to convert it into string using the following:
function parse(str, separator) {
var parsed = {};
var pairs =
str.toString().split(separator);
for (var i = 0, len = pairs.length, keyVal; i < len; ++i) {
keyVal = pairs[i].split("=");
if (keyVal[0]) {
parsed[keyVal[0]] = keyVal[1];
}
}
return parsed;
}
But in the instruction:
str.toString().split(separator);
returns me the value of:
{[object Object]: undefined}
And of nothing is turned into string.
If I use the same instruction like that:
str.split(separator);
Threw me the error of:
Uncaught TypeError: str.split is not a function
And from what I've searched on the web I saw that I have to convert the str which is a Hashtable result into string.
I did that but unfortunately without any success
Is someone to help me on this issue?

Looks like you need something like this:
function parse(map, separator) {
return Object.keys(map).reduce((data, key) => {
data.push(`${key}${separator} "${map[key]}"`);
return data;
}, []).join('\n');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Related

Parse ajax response object data

I'm passing an object using the jQuery $.post method. When it's loaded using the $.get method, I need that the message field of the object is parsed correctly. I was able to remove the equal "=" sign and the "&" sign, but if it's a long message it will contain the plus "+" sign and the commas are not displayed correctly. Here is the console output i get:
{user: "demo", message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipisci…+qui+officia+deserunt+mollit+anim+id+est+laborum."}
message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+Ut+enim+ad+minim+veniam%2C+quis+nostrud+exercitation+ullamco+laboris+nisi+ut+aliquip+ex+ea+commodo+consequat.+Duis+aute+irure+dolor+in+reprehenderit+in+voluptate+velit+esse+cillum+dolore+eu+fugiat+nulla+pariatur.+Excepteur+sint+occaecat+cupidatat+non+proident%2C+sunt+in+culpa+qui+officia+deserunt+mollit+anim+id+est+laborum."
user: "demo"
__proto__: Object
The commas are replaced by the %2C character and the spaces are replaced from the plus sign.
How to obtain the text without this signs?
here is a function I write for this scope, but it's not working at all.
function parseData(data){
var params = {}
params.data = data.split("&");
params.result = {};
for(var i = 0; i < params.data.length; i++) {
var item = params.data[i].split("=");
params.result[item[0]] = item[1];
}
return params.result;
}
Use this one :
function parseData(data){
return decodeURIComponent((data + '').replace(/\+/g, '%20'));
}
Use this function hope it will work for you :
export function parseData(data) {
url = decodeURI(url);
if (typeof url === 'string') {
let params = url.split('?');
let eachParamsArr = params[1].split('&');
let obj = {};
if (eachParamsArr && eachParamsArr.length) {
eachParamsArr.map(param => {
let keyValuePair = param.split('=')
let key = keyValuePair[0];
let value = keyValuePair[1];
obj[key] = value;
})
}
return obj;
}
}

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

How to replace the string value with slashes in an array while querying into mongodb?

I am trying to store the array value coming from html in the server side mongodb. the array is coming in the form of strings ie for example ["home","sports"] but i need to store in the form of slash array ie [/home/,/sports/]. i tried with using replace function in javascript but i failed doing that.
Here is my code what I tried: in my server side controller:
var sample = [];
sampleArray = ["home","sports"]; //coming from html search query.
if(sampleArray != 0){
for (var i = 0; i < sampleArray .length; i++) {
var eg3 = sampleArray [i];
console.log('value form an array' + eg3);
sample.push(eg3);
}
var test = sample.replace(/"/g, "/");
}
// querying my DB
mongoQuery = {
ProCat: {
$elemMatch: {
"title": {
$in: test //expected output [/home/,/sports/] but i am getting ["home","sports"]
}
}
}
}
If you want to convert a String Array to RegEx array, you can use RegEx constructor and Array map().
es6:
const regexArray = ["home","sports"].map(x=>new RegExp(x));
console.log(regexArray);
es5 code converted online
"use strict";
var regexArray = ["home", "sports"].map(function (x) {
return new RegExp(x);
});
console.log(regexArray);

Javascript replace parts of string to variables

I wish to do a search and replace in a string. It searches for any word that begins with "$" and replaces it with a value from an array. For example if the string is:
[div class='news'][h4]$title[/h4][p]$desc[/p][/div]
It replaces [] to <> (already done). But then i want it to replace $title with data from an array. So data["title"] and then $desc would be replaced with data["desc"].
The code i have so far is
var obj = $('#'+id);
var url = $(obj).attr('loadJSON');
var format = $(obj).attr('responseFormat');
$.getJSON(url, function(data) {
var html = "";
for(var i=0;i<data.length;i++) {
var tmp = format;
tmp = tmp.replace(/\[+(.*?)\]+/g,"<$1>");
tmp = tmp.replace();
}
});
The format is the string which it will replace in, and data (from the JSON response) is the array which i want the variables to change to.
Could someone please help me with this? Thanks in advance
then add as last replacement
tmp = tmp.replace(/\$([a-z]+)/gi, function(match, v) {
return data[v] || v;
})
note that in case of data[v] is undefined you could return something else like data[v] || ["not found", v].join(' ') just to track what variable is missing
I'm no JS expert, but this looks wrong in so many ways... your data object should be a JS object, that is something like { title: 'Generic title.', description: 'It's a generic title' }.
Why not put the values into paragraph elements, and then insert those into the div (i.e., you append them). Something like this:
$.getJSON(url, function(data) {
$('div.news').append($('<p />').text(data.title));
$('div.news').append($('<p />').txt(data.description));
});
You could do
tmp = tmp.replace(/\$([a-z]+)/gi, function(match) {
match = match.replace('$', '');
return (data[match] || match)
});
http://jsfiddle.net/uZbk8/

Categories