How to access variables inside an array - javascript

So, I have been trying to solve this all of yesterday and today but cannot figure it out. I have the following returned in a variable called
var myRequest = req.body
console.log(myRequest)
Produces the following:
{
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
}
Now, I need to access the params key, and access the first param value so that whatever is returned in the first param value string is stored as username in a variable, and whatever is returned in param value string (the second one), is stored as a password.
So the final effect something like this:
var username = myRequest.methodcall.params.param...first value string
var password = myRequest.methodcall.params.param...second value string
However, I am really struggling to understand how to do this. Im guessing forEach loops would come in this, however I do not have experience with them so would appreciate some tips.
Also, when I try doing myRequest.methodcall, I keep getting undefined returned.
Any help will be greatly appreciated!

It sounds like your value is in JSON, parse it first and then you should presumably be able to get its values:
var myRequest = JSON.parse(req.body);
var userName = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];

What you have posted is JSON. you need to set it up like:
var myRequest = JSON.parse(req.body)
this will allow you to access the it like a normal js object.

Use . to access keys in object and [] to access index in array.
This code should work:
var username = myRequest.methodcall.params[0].param[0].value[0].string[0]

If you would like to use a loop at get the values test1,password, and so on. You can use a loop and access the param array:
var params = myRequest.methodcall.params[0].param;
params.forEach(function(item){
console.log(item.value[0].string[0]);
});
Fiddle

//var myRequest = JSON.parse(req.body) // if JSON
var myRequest = {
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
};
var params = myRequest.methodcall.params;
var uname, pwd;
for (var i = 0; i < params.length; i++) {
console.log("uname is " + params[i].param[0].value[0].string);
console.log("pwd is " + params[i].param[1].value[0].string)
}

if your response structure will be same then no need to go for loop or something, just directly access the username and password from response.
try this.
var username = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];

Did you debug your code?
I mean these code:
var username = myRequest.methodcall.params.param[0];
var password = myRequest.methodcall.params.param[1];

Related

localStorage.removeItem() not removing key/value from object

Struggling to figure this one out...
I'm trying to remove a key/value pair, from my localStorage object. However, nothing gets removed. (I also don't have any errors).
I understand I can remove the key/value in question, by it's key name. Here's an example of the object:
bookMarksArray: [
{
"name": "reena",
"url": "brian"
},
{
"name": "joe",
"url": "ault"
}
]
And here's my code... I'm using event target to grab and match the key name, to the object index.
And then passing in key of that object index, into localStorage.removeItem()... What am I doing wrong?
list.addEventListener('click', event => {
if (event.target.classList.contains('js-delete-url')) {
const editName = event.target.parentElement.name.value;
const objIndex = bookMarksArray.findIndex(obj => obj.name === editName);
localStorage.removeItem(bookMarksArray[objIndex].name);
console.log('delete', bookMarksArray[objIndex].name);
}
});
Console prints this:
app.js:55 delete reena
Thank you!
LocalStoage saves the value in string format, so you have to stringify JSON object every time to save it in localStorage, we can solve this problem, please find below code snippet, useful in this scenario,
var updateStorage = function(filterName) {
var bookMarksArray= [{"name": "reena", "url": "brian"}, {"name": "joe", "url": "ault"}]
localStorage.setItem('nameList', JSON.stringify(bookMarksArray));
var items = JSON.parse(localStorage.getItem('nameList'));
var updatedList = items.filter(function(a) {
return a.name !== filterName;
});
localStorage.setItem('nameList', JSON.stringify(updatedList));
console.log(localStorage.getItem('nameList'));
// result [{"name":"reena","url":"brian"}]
};
updateStorage('joe');
//set js object to localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))
//get js object from localstorage
bookMarksArray= JSON.parse(localStorage.getItem('bookMarksArray'))
//remove desired item
bookMarksArray = bookMarksArray.filter(function(item) {
return item.name !== 'reena';
});
//update js object in localstorage
localStorage.setItem('bookMarksArray',JSON.stringify(bookMarksArray))

JAVASCRIPT object to array conversion

I search on stackoverflow before post my question, but I didn't find any solution. I have an object like this :
"{"COURRIERS":
{"05. Juridique":
[{"res_id":100,"type_label":"Plainte","subject":"test23","doctypes_first_level_label":"COURRIERS","doctypes_second_level_label":"05. Juridique","folder_level":2}]
}
}"
And I need to access it like an array, in order to get the information like res_id etc..
How can I do this ?
Thanks in advance
Assuming that you won't have more than one object/array in each layer, this should get you what you need.
let obj = {
"COURRIERS": {
"05. Juridique": [{
"res_id": 100,
"type_label": "Plainte",
"subject": "test23",
"doctypes_first_level_label": "COURRIERS",
"doctypes_second_level_label": "05. Juridique",
"folder_level": 2
}]
}
}
let folder = Object.keys(obj)[0]
let type = Object.keys(obj[folder])[0]
let result = obj[folder][type][0]
console.log(result)
You can gain access to the data in multiple ways. The following below will help clarify some of the way you can access some of the data.
myObj.type = "Dot syntax";
myObj.type = "Dot syntax";
myObj["date created"] = "String with space";
myObj[str] = "String value";
myObj[rand] = "Random Number";
myObj[obj] = "Object";
myObj[""] = "Even an empty string";
For your problem you can use the following
var x = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}};
console.log(x['COURRIERS']['05. Juridique'][0].res_id)
Something like that ?
(I insert the data inside a variable and print the wanted result with key index)
let obj = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}
};
console.log(obj["COURRIERS"]["05. Juridique"][0]["res_id"]);
EDIT
You want to acess it with variable.
For avoid bug, I strong recommend you to check if the variable value key exist in the array/object like :
let folder = 'COURRIERS';
if(folder.indexOf(data) >= 0) { // folder.indexOf(data) = 0
// ... finish the job here :)
}
// indexOf return -1 if the value is not found

Selecting a JSON object by number not by name

I try to store a JSON object with informations in multiple languages. Im not even sure they way i did it is good, any suggestions are welcome.
My current problem ist, that i dont know how to access the first language without knowing what language it is.
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
document.write(Data[1].Name);
I just want to access the second object, sometimes its "en", sometimes its "de".
Thanks for any tipps!
Here is a pure javascript solution:
First: You get the keys of the object:
var keys = Object.keys(Data);
Then: The keys are stored in a array. You can access them with an index. Like:
Data[keys[0]]
Now: You can use a foor loop or whatever you want :)
Data is an object its not array so you cant access it like Data[0] you can access it like Data.en.
but as you say you dont know any thing about en or de so i suggest that you form the Data object like this :
var Data =[{
lang:"en",
langData:{
Name:"Some name"
}
}]
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
var index = 0;
$.each(Data, function(key, val){
index += 1;
if (index == 2){
// key is the language, like in this example key is 'en'
console.log(key);
}
});
var name = (Data.en || Data.de || {})['Name'];
(Data.en || Data.de || {}) get's value of Data.en or Data.de if both doesn't exist, return empty object, so that script doesn't throw exception for Name property
()['Name'] same as myObject['Name'], myObject.Name
assign value to name variable, it will be Some name or undefined at least
If you have more languages, add them all, notice: it will return first found lang
var name = (Data.en || Data.de || Data.ru || Data.fr || {})['Name'];
Use Object.keys method to get list of object property names:
console.log(Data[Object.keys(Data)[1]]['Name']); // "Some name"

Getting json data from a nested array

I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.
var translator = function () {
for (var i = 0; i < result.length; i++)
{
//Construct URI
var source =
'https://www.googleapis.com/language/translate/v2?' +
'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
'source=en&' +
'target=fr&' +
'q=' +
result[i][1]; //looping over an array, no problem there
//Receive response from server
var to_Translate =new XMLHttpRequest();
to_Translate.open("GET",source,false);
to_Translate.send();
var translated = to_Translate.responseText;
JSON.parse(translated);
translated = translated.data.translations[0].translatedText;
console.log(translated);
}
};
translator();
Where
console.log(translated);
yields
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
My question is: how can i access the value of translatedText? I've tried:
translated.data.translations[0].translatedText;
But it doesn't seem to work. When I console.log this i get
Uncaught TypeError: Cannot read property 'translations' of undefined
translator
(anonymous function)
Let me know what you guys think!
That is just text you have to parse it with
JSON.parse(translated)
so you could access it with, for example, translated.data
UPDATE
The error you are getting means that translated.data is undefined, you have to assign the parse to a variable, otherwise it will never work, it doesn't modify it in place
var translated = JSON.parse(to_Translate.responseText);
Yes, Use
translated.data.translations[0].translatedText;
Hope it will work fine.
So close!
translated.data.translations[0].translatedText;
translations is an array of objects, and you want the translatedText property of the first element in the array.
UPDATE:
Just to confirm the output of to_Translate.responseText is a string containing:
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
So you should be able to do:
var translated = to_Translate.responseText,
parsed = JSON.parse(translated),
text = parsed.data.translations[0].translatedText;
console.log(text);

what is the preg match to extract this values using js

How to retrieve the value 100003119917070 and XgXELcliKMkSCcS from below document using preg match:
<script>
window.Env = window.Env || {};
(function(v) {
for (var k in v) { window.Env[k] = v[k]; }
})({
"user": "100003119917070",
"locale": "en_US",
"method": "GET",
"ps_limit": 5,
"ps_ratio": 4,
"svn_rev": 479734,
"static_base": "https:\/\/s-static.ak.facebook.com\/",
"www_base": "http:\/\/www.facebook.com\/",
"rep_lag": 2,
"post_form_id": "6cea66d4118fac268304a538a5004ed7",
"fb_dtsg": "AQAcBeoe",
"ajaxpipe_token": "AXgXELcliKMkSCcS",
"lhsh": "8AQGGa7eN",
"tracking_domain": "https:\/\/pixel.facebook.com",
"retry_ajax_on_network_error": "1",
"ajaxpipe_enabled": "1"
});
</script>
<script>
CavalryLogger=false;
window._incorporate_fragment = true;
window._script_path = "\/home.php";
window._EagleEyeSeed="Se1E";
</script>
Just access window.Env.user and window.env.ajax_token?
You've put(copy) the object into the window.Env, so you can run this code:
console.log(window.Env.user, window.Env.ajaxpipe_token)
and it will print values which you want on console.
Also, you can use window.Env['user'] to reference the value 100003119917070.
if use preg,
var preg_user= /"user":\s?"([0-9]+)/;
var preg_token = /"ajaxpipe_token":\s?"([\d\w]+)/;
and you can get value by:
var user = str.match(preg_user);
var token = str.match(preg_token);
May this can help you.
In the specific example given ajaxpipe_token does not contain values other than text and numbers, but, if your value can contain other values (like it can in facebook), change your match group to look for non-quotes, then terminate with the quotes. This is the full code for extracting the values from the document.
scriptxpath ='//script[contains(.,"ajaxpipe_token")]';
scriptrslt = document.evaluate(scriptxpath,document,null,XPathResult.ANY_TYPE,null);
scriptobj = scriptrslt.iterateNext()
scriptiHTML = script.innerHTML;
user_search = scriptiHTML.match(/"user":\s?"([0-9]+)"/);
ajaxpipe_token_search = script_iHTML.match(/"ajaxpipe_token":\s?"([^"]+)"/)
user = user_search[1];
ajaxpipe_token = ajaxpipe_token_search[1];

Categories

Resources