I have a global object abc with the following structure
abc = {
dir_content: {
dir: [
"hi"
]
files: [
"1.txt",
"2.txt"
]
}
directory: "greeting"
}
hope I got the notations correct.
dir_content has its values passed from a JSON object by abc.dir_content = data;
I have a function as below
function show_dir() {
console.log(abc.dir_content.dir);
console.log(abc.directory);
}
I am expecting console.log(abc.dir_content.dir) to show hi. But its saying its undefined instead. console.log(abc.directory) shows greeting just fine.
Adding: I can print the correct results in the console with console.log(abc.dir_content.dir) . But it says undefined when called in the function.
I need to loop through the arrays of dir and files in the function. But now I stuck at getting js to read the values in the function.
Edit: I found something wrong this my global object declaration. fiddle link http://jsfiddle.net/xh5YH/ . Whats wrong with the anonymous function declaration?
abc = {
dir_content: {
// array of one dir
dir: [ "hi" ],
// array of two files
files: [
"1.txt",
"2.txt"
]
},
directory: "greeting"
}
dir_content: {
dir: {
key: "hi"
},
files: {
key1: "1.txt",
key2: "2.txt"
}
}
Notice the difference between [], () and {}
[] means you are creating an array, but you need an Object, hence the {} brackets.
Also, the returned dir_content is not structured correctly. An Object is always structured like this:
{ key: 'content' }
That is why I've added key, key1 and key 2 to the returned data. If you manage to structure the data correctly, everything will work.
Related
I have an array of objects like
[
{
"id":17368,
"creationDate":1566802693000,
"status":"InProgress",
"type":"NEW",
"agentType":"Master"
},
{
"id":17368,
"creationDate":1566802693000,
"status":"InProgress",
"type":"NEW",
"agentType":"Master"
},
{
"id":17368,
"creationDate":1566802693000,
"status":"InProgress",
"type":"NEW",
"agentType":"Master"
},
{
"id":17368,
"creationDate":1566802693000,
"status":"InProgress",
"type":"NEW",
"agentType":"Master"
}
]
But when trying to access the object property 'id' using console.log(array[0].id) throws a "cannot read property id of undefined error"
However just logging the first object with console.log(array[0]) prints the object successfully.
{id: 17368, creationDate: 1566802693000, …}
Also printing the list of ids using array.map(x => console.log(x.id)) prints the list of ids successfully .
I am in a situation where i need to access the first few specifically . Where am i going wrong ?
try this console.log(array[0] && array[0].id)
or you can use get from lodash-es like this:
import { get } from 'lodash-es'
const id=get(array[0], 'id', '')
My page object is structured so that I have all of the elements in an object and then an array of objects containing data about the fields that can be looped over to test max char length and error texts.
I would like the locator to reference a property that is outside the array so that the value does not need to be updated twice if the element changed.
Snippet from page object as an example...
module.exports = {
siteName: element(by.id('P662_NAME')),
fields: [
{
name: 'site name',
max: 45,
locator: element(by.id('P662_NAME'))
}
]
}
I have tried using the following with no luck...
this.siteName, this.siteName, module.exports.siteName
Is there a way to do this?
Your exporting looks pretty good. Import it correctly.
What you could do is set siteName as another variable and reference that in your fields object like this:
let siteName = "foo"; // now, updating this variable will also update the one in fields
let fields = [{
// other props
locator: siteName
}];
console.log(fields[0].locator); // expects "foo"
// module.exports = { siteName, fields };
Try this :
Export from a file like this
Sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2
var siteName = "dsdsd";
var fields = [
{
name: "site name",
max: 45,
locator: "dsdsd"
}
];
module.exports = {
siteName,
fields
};;
Get it imported like this:
import { siteName } from "./test.js";
console.log(siteName);
The backend of my webapp, written in node.js interacts with Json file, with a specific format that I thought not so complex but apparently is.
The structure of my json file is as such :
{
"data": [
{
"somefield": "ioremipsum",
"somedate" : "2018-08-23T11:48:00Z",
"someotherdate" : "2018-08-23T13:43:00Z",
"somethingelse":"ioremipsum",
"files": [
{
"specificfieldinarray": "ioremipsum",
"specificotherfieldinarray": "ioremipsum"
},
{
"specificfieldinarray": "ioremipsum",
"specificotherfieldinarray": "ioremipsum"
},
{
"specificfieldinarray": "ioremipsum",
"specificotherfieldinarray": "ioremipsum"
}
]
}
]
}
I try to make this answer fit a JS object like this :
const file = require('specificJsonFile.json');
let fileList = file;
And I need to loop through my 'files' array, for further treatments, but unfortunately, my JS object looks like this :
{ data:
[ { somefield: "ioremipsum",
somedate : "2018-08-23T11:48:00Z",
someotherdate : "2018-08-23T13:43:00Z",
somethingelse:"ioremipsum",
files: [Array] } ] }
Please forgive me if this is obvious, for I am still a beginner with JS.
That's only how console.log logs deep objects. To get a deeper output, you can use util.inspect
const util = require('util');
console.log(util.inspect(yourObject, {showHidden: false, depth: null}));
To loop each data's files, simply loop data, then its files
yourObject.data.forEach(d => {
d.files.forEach(file => console.log(file));
});
It looks like there is nothing wrong there and the console is abbreviating the log.
Try accessing the files list with the following code:
const filesList = file.data[0].files
and then
console.log(filesList) to check that it's eventually working.
Hope it helps!
let fileList = file.data[0].files;
This will create an array of only your files array.
You can console.log(fileList)
Or whatever you like with the data.
Based on your comment, try the of keyword instead of in keyword to get the behaviour you expected.
for (let file of fileList){
console.log(file);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
You can use for in
for (item in fileList.data) {
for (file in fileList.data[item].files) {
let data = fileList.data[item].files[file];
// process the data
}
}
Continuing yesterday's saga, now I can retrieve json objects in a response but I can't extract the data from them.
The following node.js snippet is from the file "accounts.js" which is in an ETrade api library that exists in the path /lib. It returns json containing data about the accounts of the authenticated user. The authentication part is working great.
exports.listAccounts = function(successCallback,errorCallback)
{
var actionDescriptor = {
method : "GET",
module : "accounts",
action : "accountlist",
useJSON: true,
};
this._run(actionDescriptor,{},successCallback,errorCallback);
};
The ETrade website says this call will produce the following sample response:
{
"AccountListResponse": {
"Account": [
{
"accountDesc": "MyAccount-1",
"accountId": "83405188",
"marginLevel": "MARGIN",
"netAccountValue": "9999871.82",
"registrationType": "INDIVIDUAL"
},
{
"accountDesc": "MyAccount-3",
"accountId": "83405553",
"marginLevel": "CASH",
"netAccountValue": "100105468.99",
"registrationType": "INDIVIDUAL"
},
{
"accountDesc": "SIMPLE IRA",
"accountId": "83405188",
"marginLevel": "CASH",
"netAccountValue": "99794.13",
"registrationType": "IRA"
}
]
}
}
In my app.js file, I have the following:
var etrade = require('./lib/etrade');
var et = new etrade(configuration);
et.listAccounts(
function(res){
var listAccountsRes = res;
console.log('account list success!');
console.log(listAccountsRes)
},
function(error) {
console.log("Error encountered while attempting " +
"to retrieve account list: " +
error);
});
When I run this code, the console log shows the following message:
{ 'json.accountListResponse':
{ response:
[ [Object],
[ [Object],
[ [Object],
[ [Object],
[ [Object],
[ [Object],
[ [Object],
[ [Object] ] } }
Suppose in app.js I want to put the accounts data in a variable called myAccounts.
One of our members, Jack, solved yesterday's problem and when I commented that I still couldn't access the data in the response, he suggested this: "That property has a dot in it so you'll have to use [ ... ] rather than dot notation to access it. See what's inside the objects with a['json.accountListResponse'].response." So far I have not been able to get that to work, even when I use ['json.accountListResponse'].res like this:
var listAccountsRes = [json.accountListResponse].res;
This returns undefined when printed to the console.
Thanks to Adam for his suggestion which led to this which works:
var listAccountsRes = res['json.accountListResponse'];
var listAccounts = listAccountsRes['response'];
console.log('account list success!');
console.log(listAccounts)
Now the console log reports almost exactly what ETrade says I should get. (They appear to have changed the name "Account" to "response"). I presume my variable listAccounts now contains the json with eight sample accounts in it that I can see in my console log. But I still don't know how to access individual elements. There should be some simple code that will iterate over the json file and produce an array of arrays that I could actually use for something. I tried accessing it like an array: console.log(listAccounts[0]) but that returns undefined. Do I need to stringify it or something?
i have a JSON js obejct in
res.metrics.load.1-min
the problem is that this is coming from the server.
i cannot extract anything as it gives illegal number
since res.metrics.load.1-min contains 1-min
Any suggestion i can i parse my JSON. my JSON is an Array
"metrics" : {
"load" : {
"1-min" : [
[
5.87,
1437031875
],
[
5.87,
1437031890
]
]}}
Please help i am using
res.metrics.load.1-min = res.metrics.load.1-min.map(
function (map)
{
return { x: map[1], y: map[0] };
});
to map values to x and y. its throwing an error.
You need to update
res.metrics.load.1-min
to
res.metrics.load["1-min"]