Backbone , changing models attributes - javascript

In a collection i need to set the value to one of attributes, but i cant find the way how do it
products.models[i].set({'category.name':'some_value'})
the rest api looks like this
{
"category": {
"id": 3,
"name": "Drink",
"icon": "staging/main/category/icon-drinks.png"
},
"id": 1,
"name": "Sugar54",
"dashboard": 1,
"last_buy": "2013-10-02",
"price": "102",
"buy_period": 7
},
How do i do that ?

If you have complex nested models, I suggest you take a look at BackboneRelational.
Otherwise in your case, you should be fine with
products.models[i].get('category').name = 'some_value';
supposing that category is a normal object.

Related

JSON weird format access data

This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},

react js :fetch data from inner array and load it to state

i have a api with peoples i am tring to dispaly names of people
"peoples": [
{
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
"id": 1,
"mainModule": "bonding2",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "jisa",
"completed": false
},
{
"id": 4,
"name": "stepy",
"completed": false
}
]
},
]
This is my data in api
I am using axios to set a state called items
axios
.get(
"url",
config
)
.then((res) => {
console.log(res.data.peoples)//this works
console.log(res.data.peoples.persons);//here i am getting error
this.setState({ items: res.data.peoples.persons}); error
}
I am trying to pass persons so I can map person names in JSX
i have changed the code pls help
Welcome to StackOverflow! As you can see in your first snippet you have an array inside peoples so the correct way to access it would be:
res.data.peoples[0].persons
Hope this solves your problem. You can read more about it in MDN docs
edit:
If you would like to iterate over persons you can do this:
res.data.peoples.map(person => (
<div key={person.id}>{person.name}</div>
));
Remember you must pass a unique key prop to the component so React can create and mantain the list correctly. More info about it in the Docs.
res.data.peoples is an array so you should iterate over it. It doesn't have persons property, it has [0], [1] etc. Try to log res.data.peoples[0].persons
From the sample data you showed, peoples is an array. So to access persons, you should be able to access it using the following, for example if you want to access the first element of the array:
res.data.peoples[0].persons
Otherwise, if you want to access it as res.data.peoples.persons then you have to change your API output such that it is like so :
"peoples": {
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
}

VueJS sum pivot table

I am learning VueJS and am in the process of porting a very simple app I wrote in Laravel with blade as the template engine.
I am keeping the existing back end which consists of a simple restful api of 3 tables: Books, Places and a pivot Books_Places.
The json looks something like this:
books:
{
"id": 1,
"title": "foo bar",
"places": [
{
"id": 1,
"name": "library 1",
"pivot": {
"book_id": "1",
"place_id": "1",
"quantity": "50",
"id": 1
}
},
{
"id": 2,
"name": "library 2",
"pivot": {
"book_id": "1",
"place_id": "2",
"quantity": "75",
"id": 2
}
}
]
}
In blade I had the following line built into a "for book in books" cycle which I loved because of its simplicity:
{{ $book->places->sum('pivot.quantity') }}
I am trying to accomplish the same in VueJS but not sure what the simplest approach is, I'd appreciate your opinions.
Thanks!
You could create a method to sum up the quantities using Array#reduce:
methods: {
sumOfQuantities: function(book) {
return book.places.reduce(function(sum, next) {
return sum + Number(next.pivot.quantity);
}, 0);
}
}
Note: Since your quantity is a string, you need to convert it to a Number (e.g. using Number()).
You can then access it in your template using v-text for example:
<div v-for="book in books">
<div v-text="sumOfQuantities(book)"></div>
</div>

Stringify JSON differently on each level

In order to hash (sha1) a JSON and to compare the resulting hash to a given one, I need a String which is exactly the same as the one that has been used to create the given hash.
Then, my stringified JSON must have different indentation for sub nodes of the JSON :
I want this js object :
{id:4,name:'patrick',roles:[{id:1,name:'admin'},{id:2,name:'author'}]}
to be stringified like that :
"{
"id": "4",
"name": "patrick",
"roles": [
{"id":1,"name":"admin"},
{"id":2,"name":"author"}
]
}"
JSON.stringify(obj,null,4) gives me something very near from the solution but not exactly :
"{
"id": 4,
"name": "patrick",
"roles": [
{
"id": 1,
"name": "admin"
},
{
"id": 2,
"name": "author"
}
]
}"
I'm trying with the second argument of JSON.stringify but can not reach my goal :'(

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

Categories

Resources