Translate service dynamically Ionic 2 Angular 2 ngx-translate - javascript

I am building an app with ionic 2 and I would like to translate some objects from the server response without storing it in a JSON file.
I´m using ngx-translate
For example, i am receiving an object like this:
{
"name": ["Hello", "Hola", "Bon Jour"],
"description": ["This text is in English", "This text is in Spanish", "This text is in French"]
}
I would like to set the value of the string in my app depending on the language selected. How can i achieve this?
Thanks so much.

You can create an object with 3 keys (en, es, fr) and then use it to set each language using 'setTranslation'
Example:
translate.setTranslation('en', translations['en']);
translate.setTranslation('es', translations['es']);
translate.setTranslation('fr', translations['fr']);
To generate this 'translations' you can iterate over the data you have and for each item, get the translation for each language using its index in the array.
let data = {
"name": ["Hello", "Hola", "Bon Jour"],
"description": ["This text is in English", "This text is in Spanish", "This text is in French"]
}
const translations = {en: [], es: [], fr: []};
Object.keys(data).forEach( key => {
translations['en'][key] = data[key][0];
translations['es'][key] = data[key][1];
translations['fr'][key] = data[key][2];
});
console.log(translations); //this will output you object ready to be used in 'setTranslation'
Here is a working fiddle with this code.
UPDATE
You can rewrite that hard-coded piece with setTranslation in a more dynamic way
Object.keys(translations).forEach( key => {
translate.setTranslation(key, translations[key]);
});
So you can have multiple (1..n) languages without having to repeat code.

Related

Javascript export excel fill top column

I created a code that can export a file via excel the code is working fine without error but my problem is the excel file has a lot of spaces can.
as you can see in the image row 123 data is put in column 7 not in column
heres my code for exporting the data
export function download() {
var header = [];
var finalData = []
var group = [
{ "group_name": "123" },
{ "group_name": "123b" },
{ "group_name": "123ef" },
{ "group_name": "Accounts Payable" },
{ "group_name": "ADG JET TEAM" },
{ "group_name": "001 Approval" }
]
var member = [
{"001 Approval": "083817 - Ranjeet Kumar (ranjeet.kumar3#concentrix.com)" },
{ "001 Approval": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{ "001 Approval": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{ "123b": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{
"123ef": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"
}
]
group.forEach(data=>{
header.push(data.group_name)
})
finalData.push(header)
header.forEach(headerData=>{
var temp = []
member.forEach(memberData=>{
if (headerData === Object.keys(memberData)[0]){
temp.push(memberData[Object.keys(memberData)[0]])
}else{
temp.push("")
}
})
finalData.push(temp)
})
exportToCsv('export.csv', finalData)}
the exportToexcel code is from here https://jsfiddle.net/jossef/m3rrLzk0/
Open your CSV in a text editor and and check the output, what are you using as separator and delimiter. This can be a CSV bad format (fields not surrounded by quotes, for ex), or a problem with excel configuration (csv delimiters and separators).
If you have data like that
field1, field2, field 3 supercool, this is a phrase, ops
It can be a problem, it should be something similar to
"field1", "field2", "field 3 supercool", "this is a phrase, ops"
In addition, try to open your csv with Google Sheets (docs), which will try to recognize the delimiters and separators automatically. See if it works.
A common problem for that is that your CSV is saparated by spaces or commas, but phrase can have a space and a comma which will be interpreted as a separator, and the whole document will break.
It can be useful to take a look at that link: Write a string containing commas and double quotes to CSV

JavaScript parsing nested JSON data

I'm creating a discord bot (using discord.js)
I'm writing a help command using pages in embeds, I have the pages working fine - however, the problem seems to come when trying to get the data from the JSON.
I have the JSON file setup in a larger config file, so it's nested inside of it.
Each command has it's name attached to it
{
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
I need to get the data from the commands area for each page.
I only have a integer input (from the page number), but I haven't got a clue how I would get the data from whatever command needs to be shown.
For something else in my project, I am using this to get the expectedArgs from the JSON object config.commands[arguments].expectedArgs, where the config is just a reference to the JSON file, this works perfectly fine. The arguments is a string input (i.e. rule), which returns whatever the info from that command.
However, would there be a way to get say the second one down (invite). I've tried config.commands[pageNumber].expectedArgs}, however, this doesn't seem to work. pageNumber would be an integer, so would it would get whatever value and then I could grab the expectedArgs.
You can get all keys from an object and select one using their index.
const json = {
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
const pageNumber = 1
// key will be a command name, e.g. 'invite'
const key = Object.keys(json.commands)[pageNumber]
const { expectedArgs } = json.commands[key]
console.log(`${key} expects ${expectedArgs}`)
Remember that indexes range starts at zero.

Querying Project Gutenberg catalog.rdf via rdflib.js

I am attempting to interpret Project Gutenberg's catalog.rdf file from the browser using rdflib.js. Currently I am able to download a cached copy of the catalogue, parse it, and match a list of books. Next, I'm trying to get all the particulars about the book (title, author, subjects, etc.)
Unfortunately, most of my literal values are coming back as [object NodeList]
Example of book RDF:
<pgterms:etext rdf:ID="etext27785">
<dc:publisher>&pg;</dc:publisher>
<dc:title rdf:parseType="Literal">A Book About Lawyers</dc:title>
<dc:creator rdf:parseType="Literal">Jeaffreson, John Cordy, 1831-1901</dc:creator>
<pgterms:friendlytitle rdf:parseType="Literal">A Book About Lawyers by John Cordy Jeaffreson</pgterms:friendlytitle>
<dc:language><dcterms:ISO639-2><rdf:value>en</rdf:value></dcterms:ISO639-2></dc:language>
<dc:subject><dcterms:LCSH><rdf:value>Lawyers -- Great Britain -- Anecdotes</rdf:value></dcterms:LCSH></dc:subject>
<dc:subject><dcterms:LCC><rdf:value>KD</rdf:value></dcterms:LCC></dc:subject>
<dc:created><dcterms:W3CDTF><rdf:value>2009-01-12</rdf:value></dcterms:W3CDTF></dc:created>
<pgterms:downloads><xsd:nonNegativeInteger><rdf:value>20</rdf:value></xsd:nonNegativeInteger></pgterms:downloads>
<dc:rights rdf:resource="&lic;" />
</pgterms:etext>
Example of code used to parse:
let store = $rdf.graph();
$rdf.parse(stm,store,baseUrl,'application/rdf+xml');
let books = store.match(undefined, types.RDF('type') , types.PGb('etext')).map(t=>t.subject);
let lib = books.map(b=>{
let props = store.match(b, null, undefined);
console.debug("Book: " + schema['_id']);
props.forEach(a=>{
console.debug(a);
});
});
This results in all the triples being returned, however the object portion is often an attempt to serialize a NodeList. For example, the "title" predicate:
{
"subject": {
"termType": "NamedNode",
"value": "http://www.gutenberg.org/feeds/catalog.rdf#etext14600"
},
"predicate": {
"termType": "NamedNode",
"value": "http://purl.org/dc/elements/1.1/title"
},
"object": {
"termType": "Literal",
"value": "[object NodeList]",
"datatype": {
"termType": "NamedNode",
"value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"
}
},
"why": {
"termType": "NamedNode",
"value": "https://example.com/datasets/gutenberg/catalog.rdf.gz"
}
}
How is it possible to get the actual value of a literal object from the RDF query?
I would also be open to other RDF JS libraries, or other query mechanisms (SPARQL for example), if that would be easier.
This behaviour is as a direct result of a defect in the library.
RDF+XML nodes with a parseType='Literal' always result in "[ojbect NodeList]" in the browser.
https://github.com/linkeddata/rdflib.js/issues/75

Angular 2: Filter by value in nested array?

I’ve been experimenting with this GitHub repo via a course on Lynda.com (https://github.com/planetoftheweb/learnangular) by Ray Villalobos -- it functions similarly to a basic web app that I’m hoping to build, but I’ve recently hit a bit of a road block.
In that repo linked above, in app/component.app.ts, is the following array:
var ARTISTS: Artist[] = [
{
"name": "Barot Bellingham",
"shortname": "Barot_Bellingham",
"reknown": "Royal Academy of Painting and Sculpture",
"bio": "Some bio here."
},
// etc...
]
This array is filtered by a pipe as seen in app/pipe.search.ts:
export class SearchPipe implements PipeTransform {
transform(pipeData, pipeModifier) {
return pipeData.filter((eachItem) => {
return eachItem['name'].toLowerCase().includes(pipeModifier.toLowerCase()) ||
eachItem['reknown'].toLowerCase().includes(pipeModifier.toLowerCase());
});
}
}
Here's the filter input:
<input class="search-input" [(ngModel)]="field1Filter" placeholder="type in search term here" (click)="showArtist(item); field1Filter=''">
And the code for the filter results:
<ul class="artistlist cf" *ngIf="field1Filter">
<li class="artistlist-item cf"
(click)="showArtist(item);"
*ngFor="let item of (artists | search: field1Filter)">
<artist-item class="content" [artist]=item></artist-item>
</li>
</ul>
<artist-details *ngIf="currentArtist" [artist]="currentArtist"></artist-details>
This all works perfectly, however, in my project, I would need to include three nested arrays, and have the ability to filter based upon the values in those arrays. A sample of the kind of array I need will look something like this:
var ARTISTS: Artist[] = [
{
"name": "Barot Bellingham",
"shortname": "Barot_Bellingham",
"reknown": "Royal Academy of Painting and Sculpture",
"bio": "Some bio here...",
"friends": [
"James",
"Harry",
"Bob",
"Liz",
"Kate",
"Jesse"
],
"emails": [
"bb#this.com",
"aa#this.com"
],
"car": [
"honda",
"scion",
"aston martin"
]
},
// etc...
]
Therefore, I hope to filter by “Harry,” and only display objects that contain “harry” in either “name,” “reknown,” “friends,” "emails," or "cars." Is this possible, and if so, how can I edit the pipe filter to do this? Thank you!!
(I'm pretty green at angular and JS in general, so I want to apologize in advance if I’ve used incorrect terminology or overlooked/misunderstood something basic.)
I deleted my prior answer because it was more confusing than helpful. I pasted example code without applying it to your variables/properties/objects and it was misleading. Let's try again:
export class SearchPipe implements PipeTransform {
transform(pipeData, pipeModifier) {
pipeModifier = pipeModifier ? pipeModifier.toLowerCase() : null;
return pipeModifier ? pipeData.filter(eachItem => {
eachItem['name'].toLowerCase().indexOf(pipeModifier) !== -1 ||
eachItem['reknown'].toLowerCase().indexOf(pipeModifier !== -1) : pipeData;
});
}
}
The first line of code in the transform method ensures that the modifier passed in is also lowercase so that the compare always compares lower case values. It also has a null check to ensure it does not try to lowercase it if it is null.
The second line of code also uses the "?" syntax to handle the case of a null pipeModifier.
I changed includes to indexOf. Includes checks arrays. Are these items, such as eachItem['name'], an array?
That should be closer.
NOTE: Without a provided plunker ... I did not check the syntax or correct execution of this code.

Get Data from JSON String

I'm unable to successfully get data from the JSON string below. Using JavaScript, I'm able to alert the full string [ alert(data); ] but I'm unable to get only the first name.
Can someone please help?
var data = {
"name": [
"Enid Norgard",
"Cassie Durrett",
"Josephine Ervin"
],
"email": [
"TheWoozyGamer#gmail.com",
"TheHabitualGamer#gmail.com",
"TheUptightGamer#gmail.com"
],
"role": [
"Gamer",
"Team Leader",
"Player"
],
"emp_id": [
"50",
"408",
"520"
],
"id": [
"234",
"444",
"235"
]
}
Looks like you have a string(because when you use alert the complete text is shown, if it was a object then [Object object] would have shown), first you need to parse it using JSON.parse()
var t = JSON.parse(data)
alert(t.name[0])
Note: Old browsers like IE8 which does not have native support for JSON you have to add a library like json2 to add JSON support
use the following code
alert(data.name[0]);
//sample code
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
Most browsers support JSON.parse(), hope this will help you for detail see link.
With data.name[0] you will get the name Enid Norgard
Similar to that use
data.name[index]
while index is the position of the name in the innerarray.
If you want only the names array use:
alert(data.name)
try this to loop through all elements
for(x in data)
{
for(y in data[x])
{
alert(data[x][y]);
}
}

Categories

Resources