javascript object literal methods to populate the objects - javascript

i have an object like this :
var data = {
scope: "some_scope",
redirect_urls: {
return_url: return_url,
cancel_url: cancel_url
},
someotherobj:{
method: "get"
},
setRedirectUrls: function(return_url, cancel_url) {
this.redirect_urls.return_url = return_url;
this.redirect_urls.cancel_url = cancel_url;
}
}
and i want to have this object JSON.strigify'ed but i miss something or i dont know if this is the right way like :
data.setRedirectUrls('http://www...','http://www....');
var json = JSON.stringify(data);
but i get ReferenceError: "return_url" is not defined.

The problem is you're trying to instantiate your objects properties with variables which haven't been defined/don't exist, change them to empty strings.
var data = {
scope: "some_scope",
redirect_urls: {
return_url: "",
cancel_url: ""
},
someotherobj: {
method: "get"
},
setRedirectUrls: function(return_url, cancel_url) {
this.redirect_urls.return_url = return_url;
this.redirect_urls.cancel_url = cancel_url;
}
}
data.setRedirectUrls('http://www...', 'http://www....');
var json = JSON.stringify(data);
console.log(json)
.as-console-wrapper {max-height: 100% !important;top: 0;}

Hey Check out my snippet, I added an explanation to my answer there.
var data = {
scope: "some_scope",
redirect_urls: {
return_url: '', // return_url: return_url; Can't do this here because they don't exist.
cancel_url: '' // cancel_url: cancel_url;
},
someotherobj:{
method: "get"
}
}
// After you know the structure of your object then add the actions to it here.
data.setRedirectUrls = function(return_url, cancel_url) {
this.redirect_urls.return_url = return_url;
this.redirect_urls.cancel_url = cancel_url;
}
data.setRedirectUrls('http://www...','http://www....');
var json = JSON.stringify(data);
console.log(json);

Related

Retrieve rows for multiple primary key values from AWS DynamoDB database

I am trying to say:
select * from myTable where pkName in ('john', 'fred', 'jane')
but there doesn't seem to be a native way to feed a list of items in an array. I have my query working and retrieving values for a single primary key but want to be able to pass in multiple ones. It seems this isn't possible from looking at the DynamoDb page in the console but is there a good workaround? Do I just have multiple OR in my KeyConditionExpression and a very complex ExpressionAttributeValues?
I'm referencing this page:
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html
And using code based on the following (which can be found at the address below):
var params = {
ExpressionAttributeValues: {
':s': {N: '2'},
':e' : {N: '09'},
':topic' : {S: 'PHRASE'}
},
KeyConditionExpression: 'Season = :s and Episode > :e',
ProjectionExpression: 'Title, Subtitle',
FilterExpression: 'contains (Subtitle, :topic)',
TableName: 'EPISODES_TABLE'
};
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html
You are looking for the batchGetItem function, documented here.
You can also use DocumentClient and batchGet.
const AWS = require('aws-sdk');
const dbClient = new AWS.DynamoDB.DocumentClient({ region: 'ap-south-1' });
exports.handler = (event, context, callback) => {
var cartItems=JSON.parse(event.body);
let scanningtable = {
RequestItems: {
COOLERS : {
Keys: [
{
"ITEM_ID": 379
},
{
"ITEM_ID": 376
}
],
ProjectionExpression: "ITEM_ID, #N,CATEGORY, SUB_CATEGORY, BRAND, SELL_RATE",
ExpressionAttributeNames: {
"#N": "NAME"
},
}
}
};
dbClient.batchGet(scanningtable, function (err, data) {
if (err) {
callback(err, null);
} else {
var response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(data),
};
callback(null, response);
}
});
};

Immutability-helper - How to update this value?

I have a JSON object stored in "aggRequest", this is my JSON
{
"state":{
"controllerStates":[
],
"rulesetStates":[
{
"rulesetContext":{
"dialog_stack":[
{
"dialog_node":"root"
}
],
"dialog_turn_counter":1,
"dialog_request_counter":1,
"_node_output_map":{
"node_1_1504607088493":[
0
]
},
"branch_exited":true,
"branch_exited_reason":"completed"
},
"convId":"XXXX",
"modelRef":"XXXX"
}
],
"selfCallCount":0,
"sysTurnCount":2,
"userTurnCount":2
},
"context":{
"conversationContext":{
"brand":"XXXX",
"channel":"XXX"
},
"userData":{
"tokens":[
]
}
},
"XXXXX":"2.0",
"XXXXX":"XXXXX",
"XXXXX":"XXXXX",
"XXXXX":"XXXXX",
"XXXXX":"XXXXX",
"turnStart":"2018-08-10T15:21:36.075Z",
"turnEnd":"2018-08-10T15:21:36.076Z"
}
I am trying to set the turnEnd to a new date using moment, the date is being created correctly, and I believe my function is correct:
const update = require('immutability-helper');
function updatePropertyValue() {
const momentDateChange = getRunDateAsString();
update(aggRequest, {
$set:
{
turnEnd: `${momentDateChange}`,
},
});
console.log(aggRequest)
}
When I view the addRequest console.log, the date has not been updated. Why would that be?
The whole idea of immutability is that you can not change the data. Instead you creating a new one. Like in the example below:
const update = require('immutability-helper');
const data = {
"turnEnd":"2018-08-10T15:21:36.076Z"
};
const newData = update(data, { $set: { turnEnd: 'voala!' } });
console.log(data); // it is immutable, right?
console.log(newData); // it is new version of the data
In order to solve the issue change your code to use updated (new version) of your data:
const updateAggRequest = update(aggRequest, { $set: { turnEnd: momentDateChange } });

Set object in data from a method in VUE.js

I have been stuck with this issues for 2 hours now and I really can't seem to get it work.
const app = new Vue({
el: '#book-search',
data: {
searchInput: 'a',
books: {},
},
methods: {
foo: function () {
axios.get('https://www.googleapis.com/books/v1/volumes', {
params: {
q: this.searchInput
}
})
.then(function (response) {
var items = response.data.items
for (i = 0; i < items.length; i++) {
var item = items[i].volumeInfo;
Vue.set(this.books[i], 'title', item.title);
}
})
.catch(function (error) {
console.log(error);
});
}
}
});
When I initiate search and the API call I want the values to be passed to data so the final structure looks similar to the one below.
data: {
searchInput: '',
books: {
"0": {
title: "Book 1"
},
"1": {
title: "Book 2"
}
},
Currently I get Cannot read property '0' of undefined.
Problem lies here:
Vue.set(this.books[i], 'title', item.title);
You are inside the callback context and the value of this is not the Vue object as you might expect it to be. One way to solve this is to save the value of this beforehand and use it in the callback function.
Also instead of using Vue.set(), try updating the books object directly.
const app = new Vue({
el: '#book-search',
data: {
searchInput: 'a',
books: {},
},
methods: {
foo: function () {
var self = this;
//--^^^^^^^^^^^^ Save this
axios.get('https://www.googleapis.com/books/v1/volumes', {
params: {
q: self.searchInput
//-^^^^--- use self instead of this
}
})
.then(function (response) {
var items = response.data.items
var books = {};
for (i = 0; i < items.length; i++) {
var item = items[i].volumeInfo;
books[i] = { 'title' : item.title };
}
self.books = books;
})
.catch(function (error) {
console.log(error);
});
}
}
});
Or if you want to use Vue.set() then use this:
Vue.set(self.books, i, {
'title': item.title
});
Hope this helps.
yep, the problem is about context. "this" returns not what you expect it to return.
you can use
let self = this;
or you can use bind
function(){this.method}.bind(this);
the second method is better.
Also google something like "how to define context in js", "bind call apply js" - it will help you to understand what is going wrong.
// update component's data with some object's fields
// bad idea, use at your own risk
Object
.keys(patch)
.forEach(key => this.$data[key] = patch[key])

promise mapping array of objects with array values

Kind of lost when iterating over promises, im trying to transform this:
[{
' site' : ['url', 'url', 'url']
},
{
' site' : ['url', 'url', 'url']
}]
so that it becomes:
[{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
},
{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
}]
So far I created the function below, but for some reason checkBranding is not called.
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function(sitesObj){
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function(url){
return searchPage(url).then(function(html){
var tempObj = {}
tempObj[url] = checkBranding(url, html, brand)
return tempObj
})
})
return sitesObj;
})
}
Thanks for the help!
You can use bluebird.js's props() method.
// You must use bluebird to achieve this
var Promise = require('bluebird');
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function (sitesObj) {
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function (url) {
return searchPage(url)
.then(function (html) {
// Use promise.props(). It resolves all properties of a
// object before returning. If there are any properties that
// arent promises they are returned as normal.
return Promise.props({
url: checkBranding(url, html, brand) // Assuming checkBranding() returns a promise.
});
});
});
return sitesObj;
});
}

Export table values Meteor Blaze

I am running into some difficulty exporting a table to csv in meteor/blaze. I am following: [http://rafaelquintanilha.com/export-your-json-data-to-csv-format/][1].
I have a Template.event that is triggering the export button
Template.export.onCreated( () => {
Template.instance().subscribe('table');
});
Template.export.helpers({
exportContacts() {
return Contacts.find();
}
});
Template.export.events({
'click .export-data' () {
MyAppExporter.exportAllContacts();
}
});
it is calling exportAllContacts() in a global helper
MyAppExporter = {
exportAllContacts: function() {
var self = this;
Meteor.call("exportContacts", function(error, data) {
if ( error ) {
alert(error);
return false;
}
var csv = Papa.unparse(data);
self._downloadCSV(csv);
});
},
_downloadCSV: function(csv) {
var blob = new Blob([csv]);
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
a.download = "contacts.csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
and the helper is calling a Meteor.method exportContacts
Meteor.methods({
exportContacts: function() {
let fields = [
"Email",
“Some Contact",
"Created Date",
"Hard Bounce",
"Unsubscribed"
];
let data = [];
let contacts = Contacts.find().fetch();
for(let i = 0; i < contacts.length; i++) {
let contact = contacts[i];
let contactString = JSON.stringify(contact);
_.each(contactString, function(c) {
console.log("Inside Loop", contactString);
data.push([
c.contact.emailAddress,
c.contact.someContact,
c.contact.creationDate,
c.contact.hardBounceBack,
c.contact.unsubscribed
]);
console.log("DATA", data)
return {fields: fields, data: data};
});
}
}
});
I keep getting an error that “emailAddress is not defined exportContacts.js:20:17
20160426-22:00:47.957(-4)? Inside Loop {"_id":"dRnXRdZrbR9CYdmBx","contact":[{"emailAddress":"fred#weasly.com","someContact":"No","creationDate":"N/A","hardBounceBack":"N/A","unsubscribed":"N/A"}]}
I20160426-22:00:48.029(-4)? Exception while invoking method 'exportContacts' ReferenceError: emailAddress is not defined
I20160426-22:00:48.029(-4)? at server/methods/exportContacts.js:20:17
I20160426-22:00:48.029(-4)? at Function._.each._.forEach (packages/underscore.js:142:22)
I20160426-22:00:48.029(-4)? at _loop (server/methods/exportContacts.js:17:7)
but I cannot seem to figure out how to access the contacts. I am logging it out (see above in logs). Any help would be appreciated.
ADDED LOGS
let contacts = Contacts.find().fetch(); console.log(contacts)
I20160427-09:06:23.484(-4)? CONTACTS [ { _id: 'dRnXRdZrbR9CYdmBx', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)? { _id: 'LHmW4R9PLM5D7cZxr', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)? { _id: 'jBdqQXz2b8itXJowX', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)? { _id: 'bnDvNGX3i879z4wr2', contact: [ [Object] ] } ]
c.contact[0].emailAddress logged out
I20160427-09:22:08.142(-4)? Inside Loop {"_id":"dRnXRdZrbR9CYdmBx","contact":[{"emailAddress":"fred#weasly.com","someContact":"No","creationDate":"N/A","hardBounceBack":"N/A","unsubscribed":"N/A"}]}
I20160427-09:22:08.217(-4)? Exception while invoking method 'exportContacts' TypeError: Cannot read property '0' of undefined
I20160427-09:22:08.217(-4)? at server/methods/exportContacts.js:21:7
I20160427-09:22:08.217(-4)? at Function._.each._.forEach (packages/underscore.js:142:22)
I20160427-09:22:08.217(-4)? at _loop (server/methods/exportContacts.js:18:7)
I20160427-09:22:08.218(-4)? at [object Object].exportContacts (server/methods/exportContacts.js:15:46)
Within the _.each loop you are accessing the wrong data items. You can also use a _.each loop instead of the outer for loop too. If you do :
let contacts = Contacts.find().fetch();
_.each(contacts, function(contact) {
_each(contact.contact, function(c) {
data.push(
{
"email": c.emailAddress,
"contact": c. someContact,
"creationDate" : c.creationDate,
"bounceBack": c.hardBounceBack,
"unsubscribed": c.unsubscribed
}
})
})
This should solve your problem. This way you are looping through the outer contacts that is coming back from the fetch and then looping through the contact array from each element. This should be the most direct way to get down to the data you are looking for.
Your problem is this line: _.each(contactString, function(c) {
It should read: _.each(contact, function(c) {
:)

Categories