How to access object array using javascript with variable - javascript

var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
var parametersForTranslation = {};
function __tr(src, params) {
parametersForTranslation[src] = params;
return buildMessage(src);
}
function buildMessage(src){
var message=dict[src] ? dict[src].message : src
console.log(message);
var messageArray = message.split("$");
var output = "";
messageArray.forEach(function(elem, index){
if(index === 0){
output += elem;
}else{
// get variable and index
var paramIndex = configMigratedTo.substring(0, 1);
var paramValue = parametersForTranslation[src][paramIndex-1];
output += paramValue;
output += configMigratedTo.substring(1);
}
});
return output;
}
__tr("configMigratedTo", [2]);
console.log(buildMessage("configMigratedTo"));
i want get result like __tr("configMigratedTo", [2]);
then it will give me
Migrated configuration to configurator: 2
i do not know where is wrong in my code

Try this one. Hope it helps!
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params)
{
for (var key in dict)
{
if (key === src)
{
var message = dict[key].message;
return message.substring(0, message.length - 2) + params[0];
}
}
return;
}
console.log(__tr("configMigratedTo", [2]))
https://jsfiddle.net/eLd9u2pq/

Would that be enought?
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: "
}
}
function buildMessage(src,param){
var output = dict[src].message + param;
return output;
}
console.log(buildMessage("configMigratedTo",2));

You are overcomplicating this, it's much easier using a regex and passing a function as replacer
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params) {
if (! dict[src]) return src;
if (! /\$0/.test(dict[src].message)) params.unshift('');
return dict[src].message.replace(/\$(\d)+/g, (orig, match) => params[match] || orig);
}
console.log(__tr("configMigratedTo", [2]));

Related

Async call in javascript For Loop not working

I have a callback function inside a loop here for (var res in results) {
but it seems the loop is not waiting for the async call. When I am calling self.callTestOutputData(test_output_url) here, the loop is not waiting fpor the response but continuing for the next iteration and I am losing out the value to push into obj.requistion_number = testOutputResponse.value;
Please note : var results = response.results Here results is an array of Json objects.
Edit 1 : I tried forEach but that didn't work .
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})
Original Code:
self.downloadDailyExcelProcurement = function (filters, excelTmpArr) {
self.disableExcelDownloadProcurement(true);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "gray";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "#D8D8D8";
var payload = {};
if (typeof filters === "string") {
var fill = filters;
} else {
var fill = self.sendFilters();
if(self.app() === "fusion"){
fill += '&module=Procurement';
}else if (self.app() === "o2r"){
fill += '&module=O2r';
}
}
if(fill.includes("%3A")){
fill = fill.replace(/%3A/g, ':');
}
payload.Endpoint = 'executions/testcollection/' + fill;
//console.log(payload.Endpoint)
payload.BeforeSend = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('guest:oracle123'));
$(".custom-loader-circle").show();
};
payload.OnSuccess = function (response) {
var results = response.results;
for (var res in results) {
var obj = {}
obj.ferp = results[res].name;
obj.po = "NA"
obj.receipt_no = "NA"
var test_output_url = results[res].reference_test_cases[0].automation_tests[0].test_outputs[0]
$.when(self.callTestOutputData(test_output_url)).done(function (testOutputResponse) {
if(testOutputResponse)
obj.requistion_number = testOutputResponse.value;
else {
obj.requistion_number = "NA";
}
self.excelTmpArr().push(obj);
});
}
else {
self.excelTmpArr().push(obj);
}
}
if (response.next) {
filters = ((response.next).split('testcollection'))[1];
if (filters[0] === "/") {
var test = filters.slice(1, filters.length);
}
self.downloadDailyExcelProcurement(test, self.excelTmpArr());
} else {
if (results.length === 0) {
$(".custom-loader-circle").hide();
self.disableExcelDownloadProcurement(false);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "#4d0000";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "white";
showMessage(self.messages, "No Data to Download", '', 'info');
} else {
self.formatForExcel(self.excelTmpArr(), fill, "Procurement");
}
}
};
payload.OnError = function (data) {
showMessage(self.messages, data.status, data.statusText, 'error');
$(".custom-loader-circle").hide();
};
getData(payload);
}
Try using async and await :
async function asyncCall () {
// call here
}
for (var res in results) {
const response = await asyncCall();
}
var results = response.results;
if(result.length > 0){
results.map((data,index)=>{
//write your code here
})
}
This will help you ..
Use forEach() to iterate since it creates its own function closure:
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})

How to convert xml to JSON in suitescript 2.0

I have an XML response that i want to convert it to JSON, i'm currently usingg XPath
var responseNode = xml.XPath.select({
node : xmlDocument,
xpath : '//SOAP-ENV:Envelope'
});
and it is not very efficient because to extract data from one xml tag, i have to write a lot of extra code. I tried using external libs with suitescript but they didn't worked. Is there any better way to convert XML to JSON
I have a project that needs to convert xml to json rencently, so I wrote the following function.
require(['N/xml'], function (xmlMod) {
//This function refer to https://davidwalsh.name/convert-xml-json
function xmlToJson(xmlNode) {
// Create the return object
var obj = Object.create(null);
if (xmlNode.nodeType == xmlMod.NodeType.ELEMENT_NODE) { // element
// do attributes
if (xmlNode.hasAttributes()) {
obj['#attributes'] = Object.create(null);
for (var j in xmlNode.attributes) {
if(xmlNode.hasAttribute({name : j})){
obj['#attributes'][j] = xmlNode.getAttribute({
name : j
});
}
}
}
} else if (xmlNode.nodeType == xmlMod.NodeType.TEXT_NODE) { // text
obj = xmlNode.nodeValue;
}
// do children
if (xmlNode.hasChildNodes()) {
for (var i = 0, childLen = xmlNode.childNodes.length; i < childLen; i++) {
var childItem = xmlNode.childNodes[i];
var nodeName = childItem.nodeName;
if (nodeName in obj) {
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [
obj[nodeName]
];
}
obj[nodeName].push(xmlToJson(childItem));
} else {
obj[nodeName] = xmlToJson(childItem);
}
}
}
return obj;
};
var str = '<?xml version="1.0"?><ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="="><SD TITLE="A" FLAGS="" HOST="davidwalsh.name"><TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else">Hello World</TITLE><LINKSIN NUM="1102">Netsuite</LINKSIN><SPEED TEXT="1421" PCT="51"/></SD><SD><POPULARITY URL="davidwalsh.name/" TEXT="7131"/><REACH RANK="5952"/><RANK DELTA="-1648"/></SD></ALEXA>';
var xmlObj = xmlMod.Parser.fromString({
text: str
});
var jsonObj = xmlToJson(xmlObj.documentElement);
log.debug('jsonObj', jsonObj);
});
The cenvert function referred to David Walsh's function located at: https://davidwalsh.name/convert-xml-json
I just revised it compatible with Netsuite.
Hope it works for you.
Here's a sample function from my NetSuite environment. I did not write this,but it is currently working.
//*********** PARSE XML INTO JSON ***********
function nsXMLToJSON(node){
var obj=nsXMLToJSONDirty(node);
var cleanObj=cleanObject(obj,true);
return cleanObj;
//*********** HELPER FUNCTIONS ***********
function nsXMLToJSONDirty(node){
var obj={};
if(!'nodeType' in node){
return obj;
}
if(node.nodeType==1 || node.nodeType=='ELEMENT_NODE'){
if(Object.keys(node.attributes).length > 0){
obj["#attributes"]={};
for(var j in node.attributes){
var attribute=node.attributes[j];
if(attribute){
obj["#attributes"][attribute.name]=attribute.value;
}
}
}
}else if(node.nodeType==3 || node.nodeType=='TEXT_NODE'){
obj=node.nodeValue;
}
if(node.hasChildNodes()){
var childNodes=node.childNodes;
for(var k in childNodes){
var item=childNodes[k];
var nodeName=item.nodeName;
if(typeof (obj[nodeName])=="undefined"){
obj[nodeName]=nsXMLToJSONDirty(item); //run the function again
}else{
if(typeof (obj[nodeName].push)=="undefined"){
var old=obj[nodeName];
obj[nodeName]=[];
obj[nodeName].push(old);
}
obj[nodeName].push(nsXMLToJSONDirty(item));
}
}
}
return obj;
}
function cleanObject(myobj,recurse){
var myobjcopy=JSON.parse(JSON.stringify(myobj));
for(var i in myobjcopy){
if(recurse && typeof myobjcopy[i]==='object'){
if(i=="#text"){
delete myobjcopy[i];
} else {
//Check if it only contains a text object
if(Object.keys(myobjcopy[i]).length==1){
if(typeof myobjcopy[i]['#text'] != "undefined"){
if(myobjcopy[i]['#text'] || myobjcopy[i]['#text']==0){
myobjcopy[i]=myobjcopy[i]['#text'];
}
}
}else{
//Handle empty objects
if(Object.keys(myobjcopy[i]).length==0){
myobjcopy[i]=undefined;
}
}
if(myobjcopy[i]){
myobjcopy[i]=cleanObject(myobjcopy[i],recurse);
}
}
}
}
return myobjcopy;
}
}
create a helper.js file so the function can be shared across different scripts.
define(["N/xml"], function (xml) {
function xmlToJson(text) {
function xmlNodeToJson(xmlNode, obj) {
var sibling = xmlNode;
while (sibling) {
if (sibling.nodeType == xml.NodeType.COMMENT_NODE) {
sibling = sibling.nextSibling;
continue;
}
if (sibling.nodeType == xml.NodeType.TEXT_NODE) {
if (!!sibling.nodeValue.replace(/[\n| ]/g, ''))
obj[sibling.nodeName] = sibling.nodeValue;
sibling = sibling.nextSibling;
continue;
}
var childObj = Object.create(null);
if (!!sibling.hasAttributes()) {
Object.keys(sibling.attributes).forEach(function (key) {
childObj[key] = sibling.getAttribute({ name: key });
});
}
var value = xmlNodeToJson(sibling.firstChild, childObj);
if ((sibling.nodeName in obj)) {
if (!Array.isArray(obj[sibling.nodeName])) {
obj[sibling.nodeName] = [obj[sibling.nodeName]];
}
obj[sibling.nodeName].push(value);
} else {
obj[sibling.nodeName] = value;
}
sibling = sibling.nextSibling;
}
return obj;
}
var xmlDocument = xml.Parser.fromString({ text: text });
return xmlNodeToJson(xmlDocument.firstChild, Object.create(null));
}
return {
xmlToJson: xmlToJson
}
});
import the helper file and use the xmlToJson function in your script.
define(['N/file', '/SuiteScripts/PATH_TO_HELPER_FILE/helper'], function(file, helper) {
...
var string = file.load({ id: '/SuiteScripts/PATH_TO_FILE/filename.xml' }).getContents()
var json_object = helper.xmlToJson(string);
...
})

toString method on Linked List implementation not working in js

I'm working through Cracking the Coding Interview and I thought I'd implement all the data structures in JS 5. Can anyone explain to me why my toString method isn't working?
Thanks!
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
Node.prototype.toString = function(head) {
console.log(head)
if (head == null) {
return ""
} else {
return head.data.toString() + "-> " + head.next.toString();
}
}
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(ll.toString())
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
};
Node.prototype.toString = function() {
var returnValue = String(this.data);
if (this.next) {
returnValue = returnValue + "-> " + String(this.next);
}
return returnValue;
};
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(String(ll))
or avoid this kind of problems completly and do not use prototype, class, this, call, etc
Your toString function takes an argument, but you're not passing it when you call toString.
If you want to access the node, you should use this, instead of passing in a value
Node.prototype.toString = function() {
var result = this.data.toString();
if (this.next) {
result += "-> " + this.next.toString();
}
return result;
}

es6 code broken in es5

I have been trying to translate my code from es6 to es5 because of some framework restrictions at my work... Although I have been quite struggling to locate what the problem is. For some reason the code does not work quite the same, and there is no errors either ...
Can someone tell me If I have translated properly ?
This is the ES6 code :
function filterFunction(items, filters, stringFields = ['Title', 'Description'], angular = false) {
// Filter by the keys of the filters parameter
const filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
let filtered;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
for (let key of filterKeys) {
if (key !== 'TextInput') {
filtered = filtered.filter(item => {
// Make sure we have something to filter by...
if (filters[key].length !== 0) {
return _.intersection(filters[key], item[key]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (key === 'TextInput') {
filtered = filtered.filter(item => {
let searchString = "";
// For each field specified in the strings array, build a string to search through
for (let field of stringFields) {
// Handle arrays differently
if (!Array.isArray(item[field])) {
searchString += `${item[field]} `.toLowerCase();
} else {
searchString += item[field].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
return searchString.indexOf(filters[key].toLowerCase()) !== -1;
});
}
}
return filtered;
}
And this is the code I translated that partially 99% work ..
function filterFunction(items, filters, stringFields, angular) {
// Filter by the keys of the filters parameter
var filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
var filtered;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
for (var key = 0 ; key < filterKeys.length ; key ++) {
if (filterKeys[key] !== 'TextInput') {
filtered = filtered.filter( function(item) {
// Make sure we have something to filter by...
if (filters[filterKeys[key]].length !== 0) {
return _.intersection(filters[filterKeys[key]], item[filterKeys[key]]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (filterKeys[key] === 'TextInput') {
filtered = filtered.filter(function(item) {
var searchString = "";
// For each field specified in the strings array, build a string to search through
for (var field = 0; field < stringFields.length; field ++) {
// Handle arrays differently
console.log(field);
if (!Array.isArray(item[stringFields[field]])) {
searchString += item[stringFields[field]] + ' '.toLowerCase();
} else {
searchString += item[stringFields[field]].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
return searchString.indexOf(filters[filterKeys[key]].toLowerCase()) !== -1;
});
}
}
return filtered;
}
These two lines
searchString += `${item[field]} `.toLowerCase();
searchString += item[stringFields[field]] + ' '.toLowerCase();
are not equivalent indeed. To apply the toLowerCase method on all parts of the string, you'll need to wrap the ES5 concatenation in parenthesis:
searchString += (item[stringFields[field]] + ' ').toLowerCase();
or, as blanks cannot be lowercased anyway, just use
searchString += item[stringFields[field]].toLowerCase() + ' ';
Here is a translated code from babeljs itself, as commented above.
'use strict';
function filterFunction(items, filters) {
var stringFields = arguments.length <= 2 || arguments[2] === undefined ? ['Title', 'Description'] : arguments[2];
var angular = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
// Filter by the keys of the filters parameter
var filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
var filtered = void 0;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function _loop() {
var key = _step.value;
if (key !== 'TextInput') {
filtered = filtered.filter(function (item) {
// Make sure we have something to filter by...
if (filters[key].length !== 0) {
return _.intersection(filters[key], item[key]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (key === 'TextInput') {
filtered = filtered.filter(function (item) {
var searchString = "";
// For each field specified in the strings array, build a string to search through
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = stringFields[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var field = _step2.value;
// Handle arrays differently
if (!Array.isArray(item[field])) {
searchString += (item[field] + ' ').toLowerCase();
} else {
searchString += item[field].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return searchString.indexOf(filters[key].toLowerCase()) !== -1;
});
}
};
for (var _iterator = filterKeys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_loop();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return filtered;
}
p.s. Or there is a better way to use babeljs directly without manually converting it.

JavaScript GetLocalResourceObject from .resx file

I'm trying to get the local ressources key from .rsex file in javascript, but it doesn't work, I got error "not available".
Thanks for your help.
var key = "errMesgLength"
var val = eval('<%= GetLocalResourceObject("' + key + '") %>');
lblMessage.innerHTML = val;
Thank you Michael for help.
I have found a solution.
In C# code I have used a web method
[WebMethod()]
public static string GetLocalRessources(string key)
{
var currentLanguage = (Language)HttpContext.Current.Session["CurrentLanguage"];
if (currentLanguage == Language.French)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
}
else
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
return HttpContext.GetLocalResourceObject("~/SelfRegistration.aspx", key, Thread.CurrentThread.CurrentCulture).ToString();
}
and in JS code, I have used PageMethos call
function IsIMEI() {
var imei = document.querySelector(".txt-imei");
var lblMessage = document.querySelector(".lblMsgError");
var key;
if (imei) {
if (imei.value !== "IMEI / Serial Number") {
if (imei.value.toString().length > 7) {
imei.style.border = "";
lblMessage.innerHTML = "";
return true;
}
else {
key = "errMesgLength"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
else {
imei.style.border = "1px solid red";
key = "errMesgIMEI"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
}
function onSucess(result) {
var lblMessage = document.querySelector(".lblMsgError");
lblMessage.innerHTML = result;
}
function onError(error) {
alert(error._message);
}

Categories