My Link json test file is the following:
[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]
The javascript requesting the value, using axios:
var Links = './Links'
axios.get(Links)
.then(function(response){
console.log(response.data["google"]);
try {
var Test12 = JSON.stringify(response.data["google"]);
} catch (err) {
var Test12 = 'nothing'
}
The result is undefined.
My goal is to return the value of the input "google" or any input from the JSON and store it in the var as a string.
Since its an array of objects so you should access the values like,
response.data[0].google
OR
response.data[0]["google"]
Your data file is a list with two objects in it.
To access the google item you should access the list element.
var Test12 = JSON.stringify(response.data[0]["google"]);
Although I would change the json file to:
{"google" : "https://google.com", "bing" : "https://bing.com"}
Maybe like this:
var data=[{"google" : "https://google.com"},{"bing" : "https://bing.com"}];
data.forEach(function(el, index) {
Object.keys(el).forEach(function(val) {
console.log(val + " => " + el[val]);
});
});
Related
I am new to JavaScript and Dynamics CRM.
I have following code:
var analysisCode = Xrm.Page.getAttribute("rf_analysiscode").getValue()[0].entityValues;
As value for analysisCode, I get following output:
{
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
}
But I want to get just the rf_code. How do I retrieve that?
Parse your result to JSON like this:
const analysisCodeObj = JSON.parse(analysisCode);
Get rf_code like this:
const rfCodeObj = analysisCodeObj["rf_code"];
Try this:
analysisCode = {
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
};
let rf_code = analysisCode.rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);
If you are getting your output in String, Firstly need to parse output and then you can get any value from that json.
Try this:
analysisCode = '{"rf_name":{"name":"rf_name","value":"ABC"},"rf_code":{"name":"rf_code","value":"ABC"},"createdon":{"name":"createdon","value":"24.1.2022 10.39"}}'
let rf_code = JSON.parse(analysisCode).rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);
I followed this little how to to apply a simple api in nodejs. It is not quite my area of expertise, I am a Computer Network Analyst and although I develop applications in C ++ (simple) and C #, I have a small doubt on how to obtain the result of an array returned by the following code:
Javascript Code using Mysql ->
//
exports.findAll = (req, res) => {
const name = req.query.name;
var condition = name ? { name: { [Op.like]: `%${name}%` } } : null;
Custumers.findAll({ where: condition })
.then(data => {
res.send(data);;
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving name."
});
});
};
Access to URL to check if everything goes as expected.
http://10.1.1.254:8085/api/custumers?name=Gabriel
My result:
[
{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}
]
How could I get the values of name, cod, imgCustumer?
Im try;
axios.get(`http://10.1.1.254:8085/api/custumers?name=Gabriel`).then((res) => {
let myvar = `My result:\n\n${res.data.name}`;
console.log(myvar);
})
Result if : Undefinid
You can access object values in JavaScript like this...
let res = [{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}]
let name = res[0].name;
let cod = res[0].cod;
let igCustomer = res[0].igCustumer;
Because res is an array full of objects, you access an object with its location in the index, like res[0]. From there you can select the key/value pair in your object by using dot notation or brackets. Each method has its use.
Try something like this:
let res = [
{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}
]
console.log(res[0]['name']);
console.log(res[0]['cod']);
console.log(res[0]['igCustumer']);
The problem with your code that you are trying to access a field that does not exists. The res.data will be equal to the response of your endpoint. Your response is an array, so apparently it does not have name field. So you need to take a particular object.
const user = res.data[0]; // Taking the first user.
Then you can access its data.
user.name; // Gabriel
To find data from array, you can iterate that array and use find like this :
let res = [
{id:6,
name:"Gabriel",
cod:10,
igCustumer:"1",
createdAt:null,
updatedAt:null}
]
let myVar = res.find((item) => {
return item.name === 'Gabriel'
});
console.log(myVar.name);
console.log(myVar.cod);
console.log(myVar.igCustumer);
I am trying to retrieve the value attribute of an unsubmitted input field as parameter to a URL that opens/saves an excel file. The Parameters are supposed to be used to filter the excel file.
I have tried using a for()-loop to save the parameters into an array and then proceed to use the append() method to add them to the end of the url.
Code below shows how I am trying to singularly append each parameter one after the other
var url = new URL("file:database/reports/getCurrentStorageOverview.php?params=excel");
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.append('params', $("#searchParameter1").val());
search_params.append('params', $("#searchParameter2").val());
search_params.append('params', $("#searchParameter3").val());
search_params.append('params', $("#searchParameter4").val());
url.search = search_params.toString();
var new_url = url.toString();
window.open("database/reports/getCurrentStorageOverview.php?params=excel");
console.log(new_url);
The parameters are supposed to be added to the end of the url however the console keeps telling me the value attribute is either undefined/ when i was trying to use an array it was filling the array with 4 "undefined(s)"
it's a different aproach but since i haven't tested your method i can show u what i normally use for this case:
const querify = obj => {
return Object.keys(obj)
.map(key => {
if (typeof obj[key] === 'object') {
return querify(obj[key])
} else {
return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
}
})
.join('&') }
what this does is it takes an object like
var filters = { page: 1, length: 10, sortBy: 'id', etc... }
and turns it into a query string that looks like "page=1&length=10&sortBy=id" etc so u can use it like this:
var url = `database/reports/getCurrentStorageOverview.php?${querify(filters)}`
I have got the following JSON as an array and I am trying to filter on roles attribute but I am not able to filter the results. Please help me.
var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];
The JavaScript code which I wrote is below:
var results = data.filter(function(user) {
var roles = user.roles;
return roles.filter(function(role) {
return role == 'clientsupervisor';
});
});
Your data variable has a syntax error. You need to remove the quotes that are wrapping it.
Also a little change in your filtering code.
Change from this:
"[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}]";
To this:
[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];
See it working:
var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"], "name": "Jack", "profileId": 34533}];
var results = data.filter(function (user){
return user.roles.indexOf('clientsupervisor') > -1;
});
console.log(results);
try this, simple way
var results = data.filter(function(user) {
return user.roles.indexOf("clientsupervisor") > -1 ? true: false
});
and remove "" from data object, this is array object
var data = [{"roles":["citysupervisor"]},.....];
For instance I have some JSON data like below (The JSON data is just an example, I just want to give out some fake, make up and wrong format JSON as example)
cata :[{
name:test1,
data:['abc1, abc2' , 'abc3,abc4']
}
name:test2,
data:['abc5, abc6' , 'abc7,abc8']
}]
And indeed I need to render it to frontend, therefore I made a new object and try to push data into it
var name = "";
var key= [];
for(var i=0;i<2;i++){
name .push(cata[i].name)
key.push(cata[i].data.join(' + '));
}
var rehandle = {
name : name,
key : key
}
The above is just how i do it now, and which do no provide the desire result, i want to know how could i restore it so i can change the format from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
UPDATE version of the question:
I think i better explain it step by step:
I have some raw data
I have a row of "data" in each set of data
(E.g:data:['abc1, abc2' , 'abc3,abc4'])
I want to change it's format to abc1+abc2 , abc3+abc4 and store it to another variable
I will pass the variable store abc1+abc2 , abc3+abc4 to an object
5.Render it one by one in a table
UPDATE 2
I have seen #pill's answer, am i able to render the data like
for(var i=0;i<cata.length;i++){
var trythis = trythis + '<td>'+name[i]+'</td>' + '<td>'+data[i]+'</td>'
}
To format your data from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
you'd simply use
data.map(k => k.split(/,\s*/).join('+')).join(' , ')
or the ES5 version
data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ');
For example...
var cata = [{"name":"test1","data":["abc1, abc2","abc3,abc4"]},{"name":"test2","data":["abc5, abc6","abc7,abc8"]}];
var rehandle = cata.reduce(function(o, d) {
o.name.push(d.name);
o.key.push(d.data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , '));
return o;
}, {
name: [],
key: []
});
console.log('rehandle:', rehandle);
Note that I had to fix up your data formatting