Update values inside javascript object - javascript

I am working with the Affirm javascript API and I need to be able to update the values inside the checkout object but am having trouble doing so. I have tried what is mentioned here but it isnt working.
Basically the object looks something like this:
affirm.checkout({
"merchant":{
"user_confirmation_url":"https://example.com/checkout/",
"user_cancel_url":"https://example.com/exit"
},
"config":{
"financial_product_key":"XXXXXXXXX"
},
"shipping":{
"name":{
"full":"Blah Person"
},
"address":{
"line1":"123 example street",
"city":"Blah",
"state":"IL",
"zipcode":"12345",
"country":"US"
}
},
"billing":{
"name":{
"full":"Dirty Larry"
},
"address":{
"line1":"123 blah street",
"city":"foo",
"state":"IL",
"zipcode":"12345",
"country":"US"
}
},
"items":[
{
"display_name":"Example Product",
"sku":"123",
"unit_price":"1222",
"qty":"1",
"item_image_url":"https://example.com/kitty.jpg",
"item_url":"https://example.com/product/123"
}
],
"discounts":{
"discount_name":{
"discount_amount":0
}
},
"metadata":{
"shipping_type":"Ground"
},
"order_id":"XXXXXXXXXXXXXXXXXX",
"shipping_amount":0,
"tax_amount":0,
"total":67599
});
The above is all set on the first page load but the customer can still update items in their cart so I need to add these changes to the above object if they occur.
I have tried affirm_checkout["shipping_amount"] = 123 that doesn't update the shipping total. Neither does affirm_checkout.shipping_amount = 123 can someone tell me what I am doing wrong?

You should define the checkout object as a variable outside the context of the affirm.checkout function. This way, you can directly access the contents of the object and pass it to affirm.checkout(yourCheckoutObject);
var yourCheckoutObject = {}; //define default or placeholder values
yourCheckoutObject.shipping_amount = 2000; //amounts are expressed in integer USD cents
affirm.checkout(yourCheckoutObject); //pass the object to the checkout function

You can try this:
{
merchant: "foo bar",
config: "baz"
}
Then you can access that by
checkout.merchant = 123

Related

how to loop through array of json objects in angularjs

I have a auto search module with below json structure. I need to loop through aray of json objects and use key and value as per requirements.
I have tried below code. But with provided json object, I am able to retrieve key, but not value.
lets say, for firt, Json object, I need to retrieve 'Product Apple'., but I`m getting only link.
I tried response.data[key][0] ,but getting full json object. May I Know where I have done wrong.
I have updated plunker below
[{
"/folder1/folder2/folder3/product-1": "Product Apple"
},
{
"/folder1/folder2/folder3/product-2": "Product samsung"
},
{
"/folder1/folder2/folder3/product-3": "Product lenovo"
},
{
"/folder1/folder2/folder3/product-4": "Product Asus"
},
{
"/folder1/folder2/folder3/product-5": "Product Acer"
},
{
"/folder1/folder2/folder3/product-6": "Product Vivo"
},
{
"/folder1/folder2/folder3/product-7": "Product Oppo"
}
]
code here
Since this is marked as duplicate post., I have gone through the provided solution and found that the duplicate post has solution via javascript. But I`m looking to iterate through angularjs 'ng-repeat'.
Please find plunker below for solution I have got
[code here][1]
code here
You probably want to assign that structure to a variable, and then run an *ngFor on it, like this:
// in the component file
let results = [
{
"/folder1/folder2/folder3/product-1":"Product Apple"
},
{
"/folder1/folder2/folder3/product-2":"Product samsung"
},
{
"/folder1/folder2/folder3/product-3":"Product lenovo"
},
{
"/folder1/folder2/folder3/product-4":"Product Asus"
},
{
"/folder1/folder2/folder3/product-5":"Product Acer"
},
{
"/folder1/folder2/folder3/product-6":"Product Vivo"
},
{
"/folder1/folder2/folder3/product-7":"Product Oppo"
}
]
// in the view
<ng-container *ngFor="let result of results">
view logic goes here
</ng-container>

Optimalization of firebase query. Getting data by ids

I'm new in Firebase. I would like to create an app (using Angular and AngularFire library), which shows current price of some wares. I have list all available wares in Firebase Realtime Database in the following format:
"warehouse": {
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id2": {
"id": "id2",
"name": "name2",
"price": "15.00"
},
... //much more stuff
}
}
I'm using ngrx with my app, so I think that I can load all wares to store as an object not list because normalizing state tree. I wanted load wares to store in this way:
this.db.object('warehouse/wares').valueChanges();
The problem is wares' price will be refresh every 5 minutes. The number og wares is huge (about 3000 items) so one response will be weight about 700kB. I know that I will exceed limit downloaded data in a short time, in this way.
I want limit the loading data to interesing for user, so every user will can choose wares. I will store this choices in following way:
"users": {
"user1": {
"id": "user1",
"wares": {
"id1": {
"order": 1
},
"id27": {
"order": 2
},
"id533": {
"order": 3
}
},
"waresIds": ["id1", "id27", "id533"]
}
}
And my question is:
Is there a way to getting wares based on waresIds' current user? I mean, does it exist way to get only wares, whose ids are in argument array? F.e.
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id27": {
"id": "id27",
"name": "name27",
"price": "0.19"
},
"id533": {
"id": "id533",
"name": "name533",
"price": "1.19"
}
}
for query like:
this.db.object('warehouse/wares').contains(["id1", "id27", "id533"]).valueChanges();
I saw query limits in Angular Fire like equalTo and etc. but every is for list. I'm totally confused. Is there anyone who can help me? Maybe I'm making mistakes in the design of the app structure. If so, I am asking for clarification.
Because you are saving the ids inside user try this way.
wares: Observable<any[]>;
//inside ngOnInit or function
this.wares = this.db.list('users/currentUserId/wares').snapshotChanges().map(changes => {
return changes.map(c => {
const id = c.payload.key; //gets ids under users/wares/ids..
let wares=[];
//now get the wares
this.db.list('warehouse/wares', ref => ref.orderByChild('id').equalTo(id)).valueChanges().subscribe(res=>{
res.forEach(data=>{
wares.push(data);
})
});
return wares;
});
});
There are two things you can do. I don't believe Firebase allows you to query for multiple equals values at once. You can however loop over the array of "ids" and query for each one directly.
I am assuming you already queried for "waresIds" and you've stored those ID's in an array named idArray:
for id in idArray {
database.ref('warehouse/wares').orderByChild('id').equalTo(id).once('value').then((snapshot) => {
console.log(snapshot.val());
})
}
In order to use the above query efficiently you'll have to index your data on id.
Your second option would be to use .childChanged to get only the updated data after your initial fetch. This should cut down drastically on the amount of data you need to download.
Yes , you can get exactly data that you want in firebase,
See official Firebase documents about filtering
You need to get each waresID
var waresID = // logic to get waresID
var userId = // logic to get userId
var ref = firebase.database().ref("wares/" + userId).child(waresID);
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.val());
});
this will return only data related to that waresID or userId
Note: this is javascript code, i hope this will work for you.

how to fetch json data in scope variable angularjs

Here is my Json data
"data": {
"address": {
"postalCode": "112629",
"state": "DL",
"city": "new city",
"streetAddress": "my street"
},
"specialities": [
{
"_id": "577692f7",
"name": "Football",
"description": "game",
"__v": 0
}
]
}
$scope.test = data;
i am fetching data in html by
ng-repeat="mytest in test" than
mytest.address.city // this is working fine
mytest.specialities.name // not printing anything
i am facing the problem in accessing the specialities name i think that is because of specialities is a array but don't know how to get it.
You defined a specialities object with only one array inside
try
mytest.specialities[0].name
Update:
Also you may want to make sure that the array has at least one element, otherwise you mayget a TypeError: Cannot read property 'name' of undefined.
So the code sould look like this:
mytest.specialities.length > 0 ? mytest.specialities[0].name : '(some default value)';
Assuming there will be many specialities you should use ng-repeat to display them all.
<p ng-repeat="s in mytest.specialities"> {{s.name}} / {{s._id}} / {{s.description}} </p>
Yes mytest.specialities is array. JSON has two possible options [ ] - array, { } - object. In this situation we have array of objects - [ { /* object data */ } ] so to get object parameter first go to array element like this ( example getting first element on index 0 ):
mytest.specialities[0].name
second element:
mytest.specialities[1].name
example each:
<div ng-repeat="special in mytest.specialities">
<span>{{special.name}}</span>
</div>
of course before that set mytest to scope like:
$scope.mytest=mytest;//mytest is your data structure

How to get data from json in order to save them in database?

I am beginner in Javascript/jQuery and I am working on an interface made with KnockoutJS, so I have several models. I would like to save all the data in the database but I don't know how to do it.
I started with :
self.save = function() {
var data = ko.toJS(self);
var test = ko.toJSON(self);
console.log(test);
}
$.ajax({
url: "myURL",
data: {'carrier': data.carrier},
type: "POST",
});
and this is the result of the console.log :
{"id":1,"carrier":"1","Settings":[{"id":1,"price":{"id":1,"DeliveryStandard":"3.00","DeliveryExpress":"6.00","Details":{"id":1,"Standard":[{"id":1,"fromPrice":0,"maxPrice":"45.000"}],"Express"[{"id":1,"fromPrice":0,"maxPrice":"66.000"}]}}}}]}
I can get the value of carrier by using data.carrier but I don't know how to get the other data like DeiveryStandard, DeliveryExpress, fromPrice, maxPrice ...
Have you got an idea?
Thanks you in advance, and sorry if my question is silly!
If you format your JSON into a more readable format, with indenting, it makes it a lot easier to understand:
(though it should be noted that it is only technically JSON while in a string format, outside of that it is just a standard javascript object)
{
"id":1,
"carrier":"1",
"Settings":[
{
"id":1,
"price": { "id":1,
"DeliveryStandard":"3.00",
"DeliveryExpress":"6.00",
"Details": { "id":1,
"Standard": [{"id":1,
"fromPrice":0,
"maxPrice":"45.000"
}],
"Express" //Missing semi-colon
[{"id":1,
"fromPrice":0,
"maxPrice":"66.000"
}]
}
}
}}//One too many closing braces
]
}
First thing to note is you have 2 syntax errors, highlighted above with comments. So fix them first! (Though I wonder if they are typos as you seem to have it working at your end)
Then we can look at the structure tree to work out where the values you want are...
DeiveryStandard and DeliveryExpress are both properties of an object assigned to price, which it a property of the first item in the Settings array. So you can access them like so:
var DeliveryStandard = data.Settings[0].price.DeliveryStandard;
var DeliveryExpress= data.Settings[0].price.DeliveryExpress;
fromPrice and maxPrice are found multiple times, in both Standard and Express items. So you need to decide what version you need. If you want Standard then you can get the first item of the Standard array like so:
var standardObject = data.Settings[0].price.Details.Standard[0];
Which you can then access the properties of like:
var fromPrice = standardObject.fromPrice;
var maxPrice = standardObject.maxPrice;
I am sure you can work out how to get the Express version of the same data!
From what you seem to have been able to work out on your own, I think your problem is not knowing how to deal with the arrays. Note that arrays are defined with square brackets [], and elements within an array should be accessed with a zero-based index, for example: array[0] for the first element, and array[1] for the second element.
This should work.
console.log(data.Settings[0].price.DeliveryStandard);
Fixed some errors in your JSON.
var j = {
"id" : 1,
"carrier" : "1",
"Settings" : [{
"id" : 1,
"price" : {
"id" : 1,
"DeliveryStandard" : "3.00",
"DeliveryExpress" : "6.00",
"Details" : {
"id" : 1,
"Standard" : [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "45.000"
}
],
"Express": [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "66.000"
}
]
}
}
}
]
};
alert(j.Settings[0].price.DeliveryStandard);
alert(j.Settings[0].price.DeliveryExpress);
alert(j.Settings[0].price.Details.Standard[0].fromPrice);
alert(j.Settings[0].price.Details.Standard[0].maxPrice);

Iteration in handlebar using backbone

I'm using backbone and handlebars for templating and i'm new to this.
My current json is in the below format and the code works fine.
[
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
But when i change my json structure to something like shown below i'm having difficulty in getting things to be populated.
{
"total_count": "10",
"dataElements": [
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
}
How can i populate name, info and total_count keeping the current code structure ?
JSFiddle : http://jsfiddle.net/KTj2K/1/
Any help really appriciated.
A few things that you need to do in order for this to work.
Replace Backbone's core 'reset' on your collection with a custom one that understands the data you are passing to it. For example:
reset: function (data) {
this.totalCount = data.total_count;
Backbone.Collection.prototype.reset.call(this, data.dataElements);
}
Now when you reset your collection, it will pull the total_count out of the object you are resetting it with, and use Backbone's core reset with the dataElement array. Keep in mind you may have to do a similar thing with 'parse' if you're intending on pulling this from the server.
I'd recommend that (if your example looks anything like the real code you're working with) you reset your collection before getting to rendering.
var dataCollectionList = new dataCollection();
dataCollectionList.reset(jsonData);
var App = new AppView({model : dataCollectionList});
Now in your view's "render" method you can grab the 'totalCount' property off the collection -
render : function() {
//Should spit the total count into the element, just as an example
this.$el.append(this.model.totalCount);
//or console.log it
console.log(this.model.totalCount);
return this;
}
Voila. Side note - as someone who works with Backbone a lot, it drives me nuts when people set an attribute of something like "model" (i.e. peopleModel, itemModel, etc) and it ends up being a backbone collection. It's much clearer to name it after what it is - though some MVC purists may disagree a bit.
Also, in this code block:
_.each(this.model.models, function (myData) {
$(this.el).append(new ItemView({model:myData}).render().el);
}, this);
You don't need to do _.each(this.model.models.......). Since you're working with a collection, the collection has a built in 'each' method.
this.model.each(function (myData) { ..... } , this);
Quite a bit cleaner.

Categories

Resources