Postman Object hasOwnProperty Tests - json

I am trying to evaluate a JSON, so that I can know if the properties are correct, I have the following code:
var data = JSON.parse(responseBody);
Object.keys(data).forEach(key => {
if(data.hasOwnProperty(key)){
console.log("Have all properties");
}
});
The problem I have is that, the answer is shown to me "n" times, how can I make it show it to me only once after evaluating that the properties exist?

This should do it:
var data = JSON.parse(responseBody);
let hasProperties = true;
Object.keys(data).forEach(key => {
if!(data.hasOwnProperty(key)){
hasProperties = false;
}
});
if (hasProperties) {
console.log("Have all properties");
}

Related

Access a nested JSON object property via a single string

This line: let X = this.appGlobal.GetNavigationLanguage().data;
retuns JSON as you can see below.
I want to take NAV.REPORTS.BMAIL.TITLE.
Translate code (NAV.REPORTS.BMAIL.TITLE) is dynamically created.
X.NAV.REPORTS.BMAIL.TITLE => works
X['NAV']['REPORTS']['BMAIL']['TITLE'] => works
But keep in mind I have dynamically created translation code I need something like this:
let transCode = 'NAV.REPORTS.BMAIL.TITLE';
console.log(X[transCode]);
How I can achieve this?
test_data = {
NAV: {
REPORTS: {
BMAIL: {
TITLE: "hello"
}
}
}
}
let transCode = 'NAV.REPORTS.BMAIL.TITLE';
properties = transCode.split('.'); //--> ["NAV","REPORTS","BMAIL","TITLE"]
result = test_data
properties.forEach(function(property) {
result = result[property]
})
console.log(result) // --> hello
The short and evil route would be the following:
console.log(eval(`X.${transCode}`));
The less evil way is to use a recursive function call, this means you only look into the number of items in your string-path (rather than looping the whole collection).
const X = {
NAV: {
REPORTS: {
BMAIL: {
TITLE: 'Test'
}
}
}
}
const transCode = 'NAV.REPORTS.BMAIL.TITLE';
// Evil...
console.log(eval(`X.${transCode}`)); // Test
// Less Evil (but needs exception handling)...
function getData(input: any, splitPath: string[]) {
const level = splitPath.pop();
if (splitPath.length === 0) {
return input[level];
} else {
return getData(input[level], splitPath);
}
}
const result = getData(X, transCode.split('.').reverse());
console.log(result); // Test

How to properly create an array of JSON objects in Typescript?

I'm trying to create an array of JSON objects in typescript. And following is the approach I have used.
var queryMutations:any = _.uniq(_.map(mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
var item = {facet: "MUTATION", term: mutation.gene + " " + mutation.proteinChange}
return item;
}
else {
return {};
}
}));
var jsonString = JSON.stringify(queryMutations);
is this the correct way to do it? Appreciate your suggestions.
To me it looks ok. I'd personally make a few layout style modifications and use backtick placeholder strings.
var queryMutations:any =
_.uniq(
_.map(
mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
return {facet: "MUTATION",
term: `${mutation.gene} ${mutation.proteinChange}`
} else {
return {};
}
}
)
);
var jsonString = JSON.stringify(queryMutations);

AngularJS - Create dynamic properties to an object/model from json

OK, we all know this works:
vm.myObject = {
required : "This field requires data",
.....
}
But how can I create that same object dynamically when the property 'keys' and 'values' come from a json file, eg:
json:
[
{ "key" :"required", "value": "This field requires data"},
.....
]
service:
var myObject = {}
DynamicObjSvc.get()
.success(function(data){
data.forEach(function(item){
// pass each key as an object property
// and pass its respective value
?????????
})
.....
UPDATE:
Kavemen was mostly correct, this turned out to be the solution:
var myObject = {};
DynamicObjSvc.all()
.success(function(data){
angular.forEach(data, function(msg) {
myObject[msg.key] = msg.value; <-- his answer was incorrect here
});
$fgConfigProviderRef.validation.message(myObject);
})
.error(function(err){
console.log(err.message);
})
You can use angular.forEach and the bracket notation for setting (and getting) object properties in Javascript
var myObject = {}
DynamicObjSvc.get().success(
function(data) {
angular.forEach(data, function(value, key) {
myObject[key] = value;
});
}
);
See also Working with Objects from MDN
EDIT
I see now that your data is really an array of objects, not just a single object, so yes, the code above could lead you astray.
In any case, the method of setting an object's properties dynamically using the bracket notation is sound; the loop could be reworked to handle your data array as such:
//we have an array of objects now
var myObjects = [];
DynamicObjSvc.get().success(
function(data) {
//for each object in the data array
for(var i = 0; i < data.length; i++) {
//create and populate a new object for the ith data element
var newObject = {};
angular.forEach(data[i], function(value, key) {
newObject[key] = value;
});
//and add it to the overall collection
myObjects.push(newObject);
}
}
);

How to obtain arguments.callee.caller?

I am trying to find out the name of the function that called my Google Apps Script function, by using arguments.callee.caller as in How do you find out the caller function in JavaScript?, but it seems there's no such property exported. (However, arguments.callee exists.)
How can I get that calling function's name in Google Apps Script?
As a secondary question, why isn't arguments.callee.caller there?
I made this function:
function getCaller()
{
var stack;
var ret = "";
try
{
throw new Error("Whoops!");
}
catch (e)
{
stack = e.stack;
}
finally
{
var matchArr = stack.match(/\(.*\)/g);
if (matchArr.length > 2)
{
tmp = matchArr[2];
ret = tmp.slice(1, tmp.length - 1) + "()";
}
return ret;
}
}
It throws as Error() and then gets the function name from the stack trace.
Try vary the '2' in matchArr[2] when using wrappers.
caller is a non-standard extension to JavaScript (that is, many browsers have it but it's not part of the EcmaScript standard) and not implemented in Apps Script.
I made a function to get the call stack based on jgrotius's answer:
function getCallStack()
{
var returnValue = "";
var framePattern = /\sat (.+?):(\d+) \((.+?)\)/;
try
{
throw new Error('');
}
catch (e)
{
returnValue = e.stack
.split('\n')
.filter(function(frame, index) {
return !frame.isBlank() && index > 0;
})
// at app/lib/debug:21 (getCaller)
.map(function(frame) {
var parts = frame.match(framePattern);
return {
file: parts[1],
line: parseInt(parts[2]),
func: parts[3]
};
});
}
return returnValue;
}
This is my updated version of the other two proposed solutions:
const getStacktrace = () => {
try {
throw new Error('')
} catch (exception) {
// example: at getStacktrace (helper:6:11)
const regex = /\sat (.+?) \((.+?):(\d+):(\d+)\)/
return exception
.stack
.split('\n')
.slice(1, -1)
.filter((frame, index) => {
return frame && index > 0
})
.map((frame) => {
const parts = frame.match(regex)
return {
function: parts[1],
file: parts[2],
line: parseInt(parts[3]),
column: parseInt(parts[4])
}
})
}
}
P.S.: please not that the regex has changed and also we are ignoring the first element of the stacktrace, since it is the getStacktrace function itself.

Json and lawnchair usage

i saw below example in lawnchair documentation,
var store = new lawnchair({name:'testing'}, function(store) {
// create an object
var me = {key:'brian'};
// save it
store.save(me);
// access it later... yes even after a page refresh!
store.get('brian', function(me) {
console.log(me);
});
});
i am not sure i understood it correctly or not, but based on my understanding, i wrote code like this, (name,dtime,address are variables with value)
db = Lawnchair({
name : 'db'
}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : name,
"DateTimeOfVerification" : dtime,
"ResidentialAddress" : address
}
store.save({key:"fdetails",value:formDetails});
store.get("fdetails", function(obj) {
alert(obj);
});
});
but, in alert i did not got value, i got "[object Object]".
1) how to store multi-attribute json object in lawnchair
2) how to get that json object.
Try this:
db = Lawnchair({name : 'db'}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : "Viswa",
"DateTimeOfVerification" : "30/07/2012",
"ResidentialAddress" : "3 The Road, Etcc...."
}
store.save({key:"fdetails", value:formDetails});
store.get("fdetails", function(obj) {
console.log(obj);
alert(obj.value.candidateName);
alert(obj.value.DateTimeOfVerification);
alert(obj.value.ResidentialAddress)
});
});
1) You are storing the formDetails structure correctly.
2) obj.value is the collection you are looking for
Had you added the console.log(obj); line into your code and then inspected the console you could probably have worked this out for yourself.