Backbone. Fetch Model (JSON issue) - backbone.js

Im trying to fetch this Model in a nice way but dont really get it to work as i want.
The model gets fetched every second by a setInterval();. I do that because there is this backend system that are able to change the json that the model holds. The problem is that i dont know how to get a hold of ALL the json.
Right now i can only access "0"(question and id) and set that on the Model. I want to be able to access all the JSON and set on the Model. How would i parse that?
My json looks like this:
{
"0": [
{
"question": "lorem ispum",
"id": "1"
}
],
"1": [
{
"id": "1",
"alternative": "lorem ispum",
"percent": "14.0000",
"total": "7"
},
{
"id": "2",
"alternative": "lorem ispum",
"percent": "14.0000",
"total": "7"
},
{
"id": "3",
"alternative": "lorem ispum",
"percent": "60.0000",
"total": "30"
},
{
"id": "4",
"alternative": "lorem ispum",
"percent": "12.0000",
"total": "6"
}
]
}
And this is my Model
QuestionModel = Backbone.Model.extend({
id: "",
url: function() {
return "api/?action=getQuestionData&question_id="+this.id;
},
parse: function (response) {
return response[0][0];
}
});

Backbone does not support nested data out of the box. I would do the following:
QuestionModel = Backbone.Model.extend({
id: "",
url: function() {
return "api/?action=getQuestionData&question_id="+this.id;
},
parse: function (response) {
return { question: response["0"][0], answers: response["1"] };
}
});
Then you can access your properties like questionModel.get('question').id and your answers like questionModel.get('answers')[0].percent

Related

How to reorder map function in React

My data looks like this
data = [
{
"id": "27eb95f9",
"title": "hello",
"sort": 4
},
{
"id": "367da510",
"title": "bro",
"sup-title": "",
"sort": 2
},
{
"id": "27eb95f9",
"title": "how ",
"sort": 3
},
{
"id": "367da510",
"title": "you doing",
"sup-title": "",
"sort": 1
},
Now I want to use map funtion in React to show 'title' but I want the order to be according to "sort" in the object file. How can I do that ?
First use sort function, then map it! Please see below.
In the second exapmle you can use it to render your componenet as well.
Here can you read about sort method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
const data = [
{
"id": "27eb95f9",
"title": "hello",
"sort": 4
},
{
"id": "367da510",
"title": "bro",
"sup-title": "",
"sort": 2
},
{
"id": "27eb95f9",
"title": "how ",
"sort": 3
},
{
"id": "367da510",
"title": "you doing",
"sup-title": "",
"sort": 1
}];
const sortedTitles = data.sort((d1, d2)=>d1-d2).map((d)=>d.title);
console.table(sortedTitles);
render = data.sort((d1, d2)=>d1-d2).map((d)=>`<p>${d.title}</p>`).join("");
console.log(render);
document.getElementById("app").innerHTML = render
<div id="app"></div>
it may works, first JSON.parse(data) to have it as a object then
data.map(row => return {
...row, order : row.sort
})

MongoDB get only selected elements from objects inside an array

What I have is a collection of documents in MongoDB that have the structure something like this
[
{
"userid": "user1",
"addresses": [
{
"type": "abc",
"street": "xyz"
},
{
"type": "def",
"street": "www"
},
{
"type": "hhh",
"street": "mmm"
},
]
},
{
"userid": "user2",
"addresses": [
{
"type": "abc",
"street": "ccc"
},
{
"type": "def",
"street": "zzz"
},
{
"type": "hhh",
"street": "yyy"
},
]
}
]
If I can give the "type" and "userid", how can I get the result as
[
{
"userid": "user2",
"type": "abc",
"street": "ccc",
}
]
It would also be great even if I can get the "street" only as the result. The only constraint is I need to get it in the root element itself and not inside an array
Something like this:
db.collection.aggregate([
{
$match: {
userid: "user1" , "address.type":"abc"
}
},
{
$project: {
userid: 1,
address: {
$filter: {
input: "$addresses",
as: "a",
cond: {
$eq: [
"$$a.type",
"abc"
]
}
}
}
}
},
{
$unwind: "$address"
},
{
$project: {
userid: 1,
street: "$address.street",
_id: 0
}
}
])
explained:
Filter only documents with the userid & addresess.type you need
Project/Filter only the addresses elements with the needed type
unwind the address array
project only the needed elements as requested
For best results create index on the { userid:1 } field or compound index on { userid:1 , address.type:1 } fields
playground
You should be able to use unwind, match and project as shown below:
db.collection.aggregate([
{
"$unwind": "$addresses"
},
{
"$match": {
"addresses.type": "abc",
"userid": "user1"
}
},
{
"$project": {
"_id": 0,
"street": "$addresses.street"
}
}
])
You can also duplicate the match step as the first step to reduce the number of documents to unwind.
Here is the playground link.
There is a similar question/answer here.

Accessing JSON with HandleBars

I have this JSON:
{
{
"status": {
"success": true,
"error": ""
},
"data": {
"hello_world": [
{
"uid": {
"email": "mydx#d.com",
"id": "d3c074d8b2b24e958"
},
"my_itm": {
"name": "BIg",
"id": "2380caa99cb426f"
},
"id": "6747e005f23f451"
},
{
"uid": {
"email": "mydx#d.com",
"id": "5859082d3c074d8b2b24e958"
},
"my_itm": {
"name": "Dog",
"id": "a99cb426f"
},
"id": "c6747e005f23f452"
}
]
}
}
I'm using handlebars and I want to access from my_itm the name. But I want to do that foreach my_itm. How can I do that?
Here is what I've tried:
{{#each hello_world.my_itm}}
<p>{{name}}</p>
{{/each}}
UPDATED:
Assuming you passed the data to the template under the 'params' name:
res.render('test', {params: <your data>})
You can do this:
{{#each params.data.hello_world}}
{{#if my_itm}}
{{my_itm.name}} <br>
{{/if}}
{{/each}}
Gives:
BIg
Dog
What you have didn't work because hello_world is an array and not an object with a my_itm property you can access directly, you need to loop through the array first.
PS: You also seem to have an extra { in the json.

Get dynamic key value from an array angularjs

I have a mongo collection called settings
{
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}
Note: the values provided in my mongo is only for reference purpose.
Now I have generated an array with the records in settings collection
self.sample = function() {
self.settingsObj = {}
// console.log(self.settings)
_.each(self.settings, function(settings) {
//_.each(self.settings, function(settings) {
if (!self.settingsObj[settings.type]) {
self.settingsObj[settings.type] = []
}
self.settingsObj[settings.type] = settings.list
})
console.log(self.settingsObj)
}
When I console the settingsObj I get result like this in my console
Object {subject: Array[2], exam: Array[2]}
Now I want to loop this inside a scope variable
$scope.search = [{
"name": "",
"data": ""
}]
inside this name i want to get the object name in this situation subject,exam and inside loop i want to loop the arrays for subject and exam.
I tried another ._each, and I got the key and value but how can I loop them correctly.
Otherwise please help me in generating subject and exams as different array
I'm not very sure if I understand your question.
But if I see well you're using a Lodash.js library so I provide below script using a lodash:
I assume that you have settings variable like this:
var settings = [ {
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
,
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}];
And I create functions for process those settings:
function createSearch(settings){
return _(settings).flatMap(toSearchArray).value();
}
function toSearchArray(setting){
return _(setting.list).map("name").map(toSearchObject).value()
function toSearchObject(data){
return {
name: setting.type,
data: data
}
}
}
And when you call createSearch(settings)
you will receive this result:
[
{
"name": "subject",
"data": "Maths"
},
{
"name": "subject",
"data": " Physics"
},
{
"name": "exam",
"data": "Reading"
},
{
"name": "exam",
"data": "Fluency"
}
]
Hopefully this is what you need.

How can I get unique array from a collection of nested objects with lodash?

I have the following collection:
"items": [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Espadeiro"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Chardonnay"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
I want to grab unique grapeTypes from that collection. The returning array shold be ["Chardonnay","Espadeiro"]
What is the best way to do it with lodash?
I think this combination of pluck, map and filter should do it:
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
console.log(result);
Check the demo run below.
// Code goes here
var obj = {
items: [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Espadeiro"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Chardonnay"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
};
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>
UPD. If grapeType can be missing from properties then the script should be
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return (_.filter(obj, function(prop) {
return prop.grapeType;
})[0] || {}).grapeType;
}).compact().uniq().value();
Here's one way to do it with lodash:
_(items)
.pluck('properties')
.map(function(item) {
return _.find(item, _.ary(_.partialRight(_.has, 'grapeType'), 1));
})
.pluck('grapeType')
.uniq()
.value();
First, you get the properties arrays using pluck(). Next, you use find() to get the first object in this array that has a grapeType property. This is done using has(), and partially-applying the argument to build the callback function.
Next, you use pluck() again to get the actual property values. Finally, uniq() ensures there are no duplicates.

Resources