I've got an array of n string elements encrypted with CryptoJS : [krypt1, krypt2, krypt3, ...]
The keydecrypt is the same for each element.
I try to decrypt each element of the array and return an array of string decrypted elements like this [dekrypt1, dekrypt2, dekrypt3, ...]
My code is:
var urltodecrypt = this.url.chunk;
function decrypteach(x) {
return CryptoJS.AES.decrypt(x.toString(), keydecrypt).toString(CryptoJS.enc.Utf8);
}
var clearfileurl = urltodecrypt.map(decrypteach);
When there is 1 element in the array, everything's fine: it return an array of rightly decrypted string element.
When there is >1 elements, var urltodecrypt give still the right array (verified), but var clearfileurl return an error: Error: Malformed UTF-8 data
What am I missing?
EDIT
Tried on #vector advices a loop over each element function on this model :
var urltodecrypt = this.url.chunk;
var arrayLength = urltodecrypt.length;
for (var i = 0; i < arrayLength; i++) {
var clearfileurl = CryptoJS.AES.decrypt(urltodecrypt.toString(), keydecrypt).toString(CryptoJS.enc.Utf8);
}
console.log (clearfileurl);
Exact same result = 1 element array :ok / >1 elements array: Error: Malformed UTF-8 data
EDIT #2: question close
I just broke my first code (map) into different vars :
x.toString()
CryptoJS.AES.decrypt()
toString(CryptoJS.enc.Utf8)
I relaunched my server : everything's fine now, from 1 element array to +10 elements array.
Just in case, below my (heavy & superstitious...) tested working code:
var urltodecrypt = this.url.chunk;
console.log (urltodecrypt);
function decrypteach(x) {
var stringurl = x.toString();
var bytesfileurl = CryptoJS.AES.decrypt(stringurl, keydecrypt);
var finaldecrypturl = bytesfileurl.toString(CryptoJS.enc.Utf8);
return finaldecrypturl;
}
var clearfileurl = urltodecrypt.map(decrypteach);
console.log (clearfileurl);
Related
Seek for help to transform the xml to json. I got an input with this.
"<logRecord>
<logRecord>
<logRecord>
<class name="dto">
<logField fieldName="ID" oldValue=" " newValue="650"/>
<logField fieldName="submissionDt" oldValue="" newValue="03-12-2022"/>
</class>
</logRecord>
</logRecord>
</logRecord>"
and i want change to
[{fieldName : 'ID', oldValue : '' , newValue " '650'}.
{fieldName : 'submissionDt', oldValue : '' , newValue : '03-12-2022'}]
Is it possible? Thanks
I'm almost certain there is probably a better way of doing this, so I fully expect someone to come along and critique my attempt. However, the way I would achieve this (using the functions I know) would be using xpath to extract given values from the XML.
I've commented the code to try explain exactly what I'm doing but in essence, I'm looping over each <class> then looping each <logField> before finally looping over each of the attributes.
//First we'll take our (slightly more complex) XML input string
var xmlString = "<logRecord><logRecord><logRecord><class name=\"dto\"><logField fieldName=\"ID\" oldValue=\"\" newValue=\"650\" /><logField fieldName=\"submissionDt\" oldValue=\"\" newValue=\"03-12-2022\" /></class></logRecord><logRecord><class name=\"dto\"><logField fieldName=\"ID\" oldValue=\"\" newValue=\"123\" /><logField fieldName=\"submissionDt\" oldValue=\"\" newValue=\"19-12-2022\" /></class></logRecord></logRecord></logRecord>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
//Create a new XPathEvaluator
const evaluator = new XPathEvaluator();
//Evaluate given xpath to target every <class> found inside the XML
const classExpression = evaluator.createExpression('//class');
const classResult = classExpression.evaluate(xmlDoc, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare a final array
var arr = [];
//Loop each found instance of <class>
for (i=0; i<classResult.snapshotLength; i++) {
//Find all instances of <logField> inside of THIS <class>
const logFieldExpression = evaluator.createExpression('./logField');
const logFieldResult = logFieldExpression.evaluate(classResult.snapshotItem(i), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare an array to hold each of our <logField>s
var logFieldObj = [];
//Loop each <logField> inside of the <class>
for (j=0; j<logFieldResult.snapshotLength; j++) {
//Find all attributes for THIS <logField>
const attrEvaluator = evaluator.createExpression('./#*');
const attrResult = attrEvaluator.evaluate(logFieldResult.snapshotItem(j), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare a final object to hold each of the attributes fieldName, oldValue and newValue
var attrObj = {};
//Loop over each attribute
for (k=0; k<attrResult.snapshotLength; k++) {
//Add attribute as attributeName => attributeValue to our object
attrObj[attrResult.snapshotItem(k).localName] = attrResult.snapshotItem(k).textContent;
}
//Add our object to an array
logFieldObj.push(attrObj);
}
//Create the final resulting array
arr.push(logFieldObj);
}
console.log(arr);
I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>
I have a complex Javascript array which when written to the console looks like this :
function Standing(flagsmall, teamname, won, drawn, lost, goalsfor, goalsagainst, points) {
this.flagSmall = flagsmall;
this.teamName = teamname;
this.won = won;
this.drawn = drawn;
this.lost = lost;
this.goalsFor = goalsfor;
this.goalsAgainst = goalsagainst;
this.points = points;
}
var arrStandings = new Array();
serviceUrl = "http://cloudapp.net/odata/Standings?$expand=Team,Stage&$filter=Team/Group/GroupName eq 'A'";
var line = "";
$.getJSON(serviceUrl, function (results) {
$.each(results['value'], function (i, item) {
//calculate points
var points = (item.Won * 3) + (item.Drawn * 1);
var standing = new Standing(item.Team.FlagSmall, item.Team.TeamName, item.Won, item.Drawn, item.Lost, item.GoalsFor, item.GoalsAgainst, points);
arrStandings.push(standing);
arrStandings.sort(sortfunction);
});
});
Yet when I try to iterate through it I cannot and when I check it's length it returns 0 :
console.dir(arrStandings.length);
arrStandings.forEach(function (index) {
...
});
How do I access the objects within the array?
It's not a 100% clear from your code but looks like you are trying to print the length of the array before it has been populated.
$.getJSON is an asynchronous operation, so at the point in time when you're writing to the console it has not yet been populated.
The representation displayed in the javascript console is rendered after the array is created, when it is first accessed.
I had a similar problem when i initilized an array but i put a string key, the array was casted to Object. Return this code lenght of your array/object?
Object.keys(myArray).length
You can iterate the object using for statement:
for ( index in arrStanding ){
// your code
}
EDIT:
// here you have an array
arrStandings.push(standing);
// ...and after this line?
arrStandings.sort(sortfunction);
Regards,
Kevin
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.
have tried various things
split[6].length
String.split[6].length
along these lines without success get this error message for the last one ...
ReferenceError: "string" is not defined.
Hi Thanks for all the replies, in the end I created an array based on the index of the original array and then queried the length of that. As you can see I am having trouble removing single and double quotes from the input strings. New to javascript and its making me a little crazy lol.
// Loop through all the input messages
for (var i = 0; i < input.length; i++) {
var next = output.append(input[i]);
// Get the body of the current input message
var body = input[i].text;
// Set the body
next.text = body ;
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
// Set a property
var split = next.text.split(",");
var array1 = split[5];
var array2 = split[2];
next.setProperty("aaaLength", split.length);
next.setProperty("aaaSplitValue", split.length);
next.setProperty("aaaArray1Value", split.length);
next.setProperty("aaaArray2Value", split.length);
if (next.getProperty("BaseFilename")=="name"){
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
if(split.length>10){
next.setProperty("FullFilename","nameError"+i);
next.setProperty("BaseFilename","nameError"+i);
next.setProperty("Suffix",".err");
}
if(array1.length>10){
next.setProperty("FullFilename","nameSnameSuffixError"+i);
next.setProperty("BaseFilename","nameSnameSuffixError"+i);
next.setProperty("Suffix",".err");
}
}
Length should work if the elements are strings. See the following in action at http://jsfiddle.net/46nJw/
var parts = "foo,bar,baz,foop".split(/,/);
alert( parts[3].length ); // should alert 4
var arr = ['one','two','three']
arr[1].length
returns 3
Are you sure it is returning a string?
You can force it to convert to a string like so:
String(split[6]).length;
I don't know what you need, so I give you all the options I can think of:
var commaSeparatedString = "one, two, three";
var str = commaSeparatedString.split(",");
alert (str.length) // outputs '3'
alert (str[2]); // outputs 'three'
alert (str[2].length); //outputs '5'