Parse Json Array on new lines correctly in StreamDeckSDK - javascript

I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting. But now everything is on one line. How do iterate through the array and put them on new lines?
Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.
function setTitleStatus(context, settings) {
$SD.api.setTitle(context, "Updating...");
getResults(result => resultCallback(result, context));
}
function resultCallback(result, context) {
if (!result.hasOwnProperty("Object")) {
$SD.api.setTitle(context, JSON.stringify(result));
console.log(JSON.stringify(result, '%c%s'));
return;
}
// This is where I'd like all 3 objects to be split on new lines.
// $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.Platform + " ")
// $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.PU + " ")
// $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.EA + " ")
}
function getResults(updateTitleFn) {
let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
$.getJSON(endPoint)
.done(function (response) {
updateTitleFn({
"Platform": response[0].status,
"PU": response[1].status,
"EA": response[2].status,
});
console.log("Platform", response[0].status)
console.log("PU", response[1].status)
console.log("EA", response[2].status)
})
}
Update
If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
"\n" + result.EA + " ")
Via Screenshot

To get nicely formatted output from JSON.stringify, supply the optional arguments:
JSON.stringify(obj, null, 2)
let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];
document.getElementById('result').innerHTML =
'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
'Stringify formatted: ' + JSON.stringify(arr, null, 2);
<pre id="result"></pre>

Related

Remove concatenated strings Javascript

I'm working with the Twitter API and I'm trying to get only the first news of a tweet and its link. If I console.log tweetNews I get something like this as example:
{
text: 'exampletext. \n' +
'\n' +
'exampletext. \n' +
'\n' +
'https://examplelink',
href: 'https://examplelink
},
I would like to get only the first string of the text, removing also the link inside the text.
Down below the rest of my code:
module.exports.filterTweets = (parsedArray) => {
const filteredTweets = parsedArray.filter(
(tweet) => tweet.entities.urls.length === 1
);
const tweetNews = filteredTweets.map((x) => {
return { text: x.full_text, href: x.entities.urls[0].url };
});
console.log("tweetNews", tweetNews);
return tweetNews;
};
I'm not sure I 100% follow what you are asking for, but this should get you on your way. This shows how to get the first part of the string (up to the first line break), and how to remove (http/https) URLs:
function cleanInput(input){
let firstLine = input.split(/\s+\n\s+/)[0]
//this regex is overly simplistic, just for demo purposes
//see more complete example at https://stackoverflow.com/a/3809435/57624
let withoutURL = firstLine.replace (/http[s]?:\/\/[a-z./]+/i, '');
return withoutURL
}
let sampleData1 = {
text: 'exampletext. \n' +
'\n' +
'exampletext. \n' +
'\n' +
'https://examplelink',
href: 'https://examplelink'
};
let sampleResult1 = cleanInput(sampleData1.text)
console.log("result 1: " + sampleResult1)
let sampleData2 = {
text: 'A URL: https://examplelink.com \n' +
'\n' +
'exampletext. \n' +
'\n' +
'more',
href: 'https://examplelink'
};
let sampleResult2 = cleanInput(sampleData2.text)
console.log("result 2: " + sampleResult2)

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

Pass JavaScript Function in href

I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?
Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK

Can't save id to a variable

I'm having trouble assigning an id field to a variable.
Given this:
var temp;
if(!data.obj.id){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is',temp);
}else if(!data.obj._id){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is: ',temp);
}
console.log('**************',data.obj._id);
console.log('**************',temp);
Neither of those if statements are ever true, and the console logs return,
************ 538cdd6fca343660389d4d69
************ undefined
EDIT:
I've also tried:
if(data.obj.hasOwnProperty('id')){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is',temp);
}else if(data.obj.hasOwnProperty('_id')){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is: ',temp);
}
console.log('**************',data.obj._id);
console.log('**************',temp);
And temp is still undefined.
EDIT2:
I've changed my code to this:
var temp;
if(data.obj.hasOwnProperty('id')){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is' + temp);
}
if(data.obj.hasOwnProperty('_id')){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is' + temp);
}
console.log('**************',data.obj._id);
console.log('**************',data.obj.id);
console.log('**************',temp);
And I get:
************** 538ce08c6ced88c020ecbd07
************** 538ce08c6ced88c020ecbd07
************** undefined
You didn't log the value of data.obj.id, but presumably it is also true, like _id (in the sense that their negation returns false). Therefore, neither the first nor the second if clause are fulfilled in your example, and none of the two branches execute. It seems like you want to remove the negation operators, !, from both your if clauses, but it's hard to tell without context.

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Categories