Top and Sub Category structure - json

I need to dynamically create a json object full of cats and sub cats. My structure looks like this
var cats = {
tops: {
'top' : {
link : 'link',
subs : [
{
'sub' : {
link : 'a link'
}
}
]
}
}
};
Now I can add a top level category no problem with cats.tops[topVar] = { link : topLinkVar };
However I need to add subs categories to the top category.
I have tried a few variations such as cats.tops[topVar].subs.push( { subVar : { link : subLinkVar } } ); But this produces an undefined error.
The trick is that the sub categories need to be an array, so each top category can have many sub categories. What am I missing?

This is why coding on a saturday is bad idea. Also I am rather new to JSON.
Anyway.
The reason why I was getting the undefined error is because my new top category did not create the subs array.
The proper syntax to create the new top category looks like this:
cats.tops[topVar] = {link : topLinkVar, subs : [] };
Now
cats.tops[topVar].subs.push( { subVar : { link : subLinkVar } } );
Will work as expected

Related

Get values from multiple radio group in angular

I want to get selected radio button value then create an object to send to database, I have working example here https://stackblitz.com/edit/angular-1frcbc .I got what i expected object like this
{
lessonCode: 'test',
answers: [
{
questionCode : 'question-1',
optionCode : 'option-2'
},
{
questionCode : 'question-2',
optionCode : 'option-3'
},
]
}
but there is an error ERROR like
Error: Error trying to diff 'Option 2'. Only arrays and iterables are allowed
I believe there is something wrong in here
<input type="radio" id="{{option.order}}" [(ngModel)]="question.options" value="{{option.code}}" name="{{question.order}}">
can someone help me? any thoughts would be helpful
EDIT
i know that question.options can't assign to ngModel if i change it to something like option.order .I'm not getting object like what i expected above, if i change to something like that.
I'm pretty sure i need to change this code
getJsonResult() {
let answer: any;
let data = {
lessonCode: "test",
answers: this.data.questions.map(x => {
return {
questionCode: x.code,
optionCode: x.options
};
})
};
this.submitData = data;
console.log(JSON.stringify(this.submitData))
}
i accidentally change my code to something like this
return {
questionCode: x.code,
status: x.options.code
};
and in the html like this
<input type="radio" id="{{option.order}}" [(ngModel)]="question.options.code" value="{{option.code}}" name="{{question.order}}">
and it works and give me the same result, hope this will help someone

create a random key at just one level

In Firebase, it's possible to create a random key using .childByAutoId()
let newEntry = FBRef.child("category").childByAutoId()
newEntry.setValue(["someValue": true])
This results in a json structure like this:
{
"category" : {
"random-key-generated-by-Firebase" : {
"someValue" : true
}
}
}
I was wondering is it possible to skip the last level and arrive at a structure like this instead?
{
"category" : {
"random-key-generated-by-Firebase" : true
}
}
For swift, first create a key reference
let key = ref.childByAutoId().key
Then create a childUpdate container
let childUpdates = ["/category/\(key)": true]
Finally update
ref.updateChildValues(childUpdates)

How to count json data item ionic2

I find a new problem,
I would like to count #NAME to set array FACET[] for show #KEY
Myjson
" RESULT":{
"FACET":[
{ "#NAME" : "creator",
"#COUNT" : "20",
"FACET_VALUES":[
{
"#KEY":"Book Company1",
"#VALUE":"13"},
{
"#KEY":"Book Company1์",
"#VALUE":"10"}],
{ "#NAME" : "lang",
"#COUNT" : "70",
"FACET_VALUES":[
{
"#KEY":"tha",
"#VALUE":"33"},
{
"#KEY":"eng",
"#VALUE":"42"}
],
{ "#NAME" : "bnb",
"#COUNT" : "64",
"FACET_VALUES":[
{
.
.
.
]
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
..
<ion-label>Filterr</ion-label>
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
This value="..." I want to keep it to string for to use, but zi have know idea.
example : count #NAME = 3 (creator,lang,bnb) ,and get value="..." = 0,1,2 (0==creator ,1==lang ,2==bnb)
When I select lang I get 1 , I use this to FACET[1].FACET_VALUES , So that I get #KEY
Sorry to write wrong. My english isn't very good.
Ok. there's just a tip that I would like to point out to you. You shoud get a bit better with words. Not the English language in particular but more about explaining your current result and your desired result. I believe this will force you into learning english at a much faster pace than you're currently doing. (coming from a non-native speaker)
"I would like to count#NAME to set array FACET[] for show #KEY"
So, with the returned JSON we can do a couple of things, which do not get quite clear from immediately looking at your question (did a +1 since I don't believe it's of bad quality or isn't a good question).
So there are 3 things I should cover in my post
Counting the amount that NAME occurs
Setting an array for the FACET
Showing the KEY per FACET which seems to be the end goal.
Ok
Counting the amount that NAME occurs
So you basically already got this answer. You submitted this code
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
});
Which means you already have access to the FACET array. Counting the amount that NAME occurs can be done either by creating a for loop and checking if the name is not undefined (thus incrementing an int) or counting on the fact that NAME is always defined, thus just calling this.date.size() (if this.date is set correctly of course)
get an array for the FACET
this, you're already doing by assiging the this.date = data.json().RESULT.FACET. Your this.date now contains an array holding your FACET objects. Just see it like this: JSON (with comments which is not possible in JSON but just for demonstration purposes) =
{ FACET: // declare the main object, called FACET
[ // declaring the FACET as an Array ([] is for creating a list)
{id: 2} //initializing a child of the FACET array
,{id: 3} //initializing the second FACET child.
]
}
So, this pseudo (not realistic) JSON holds 2 objects, having id = 2 and id = 3
Ok, now you should understand a bit of JSON, let's take a look at how your code looks (taking a Businnes with multiple offices and multiple employees per office into account)
{
OFFICES" : [
{
"id" : "1",
"location" : "New York",
"employees" : [
{"id" : "1", "fullName" : "Jon Skeet"},
{"id" : "2", "fullName" : "Random Stranger"}
]
},
{
"id" : "2",
"location" : "Amsterdam",
"employees" : [
{"id" : "1", "fullName" : "Ivaro18"},
{"id" : "2", "fullName" : "Some-Random Stranger"}
]
}
]
}
This code is basically the same as your code. And the question your asking now is, taking the code from my answer, how to get all the id's or names of all the employees. (get all names of keys of facet objects)
Now let's show you in typescript
someFunction() {
this.http.get('someUrl').map(response => {
console.log(JSON.stringify(response.json())); // check what you actually retrieve
let decoded = response.json();
for(let office of decoded.OFFICE) {
console.log(office.location);
for(let employee of office.employees) {
console.log(employee.fullName);
}
}
});
}
Expected output of this program
> New York
> Jon Skeet
> Random Stranger
> Amsterdam
> Ivaro18
> Some-Random Stranger
I think this pseudo code will get you to think a bit out-of-the-box and find the answer to your question. If you can't elaborate more on what you want as output I will be glad to help you at any time (even weekends) just comment and I'll respond when I have the time!
#Ivaro18 thanks for your answers.
I want to counting the amount that #NAME
for setting an array for the FACET
and showing the KEY per FACET[] which seems to be the end goal.
Yes, you totally know what I meant.
But i want output is every #KEY of that FACET[]
Example :
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
from above ion-select is show creator , lang and bnb ,I want to If When I select lang ion-option value="..."
to keep number of "#NAME"
example counting amount of #NAME is 3 and
when I select creator is ion-option value="..." << is 0
when I select lang is ion-option value="..." << is 1
when I select bnb is ion-option value="..." << is 2
and If i get value ,I take it to goToapply() for set FACET[]
example I select bnb I get value =2 and console.log this.refine
is show 2
take it(2) to let p = this.refine , so that p = 2
take p to this.foundRepos=data.json().RESULT.FACET[p].FACET_VALUES; for show #KEY in ion-list
When I select lang output is
> tha
> eng

How can I update a through-NM-attribute in sequelize?

I've read this question and it didnt' help me, so I'm asking my own:
Let's suppose I have 2 tables joined by a NM through table using Sequelize and MariaDB:
User <-- UserItem --> Item
A single User can have many Items, and a single Item can belong to many Users. But I need a custom through attribute to store the quantity of the Item, let's call it Apples. So, according to the docs, this will be the definition:
var UserItem = Sequelize.define('UserItem', {
quantity: DataTypes.INTEGER
},
timestamps: false
});
models.Item.belongsToMany(models.User, {through: 'UserItem'});
models.User.belongsToMany(models.Item, {through: 'UserItem'});
And then I add a new relationship with the through attribute like this:
User.addItem(item, { quantity: 0 });
This works as expected. But, what if I need to update the quantity of an Item? I could do the following:
User.addItem(item, { quantity: 20 });
And the quantity of my Item will be updated to 20 in case of existing, and inserted otherwise. I don't want this. I want something like that:
User.addItem(item, { quantity: quantity + 1 });
But due to the impossibility to make queries to the join tables, I am unable to get the particular NM row for updating using the previous value.
How can I achieve this? Thanks in advance.
You still have the join table DAO as specified in the docs.
In this case though you need to know if the item is new association or not.
So it will look something like.
User.hasItem( item )
.then( exists => {
if ( !exists ) {
return User.addItem( item, { quantity : 20 } )
} else {
item.UserItem.quantity += 1;
return item.UserItem.save();
}
} )
You can read more about hasAssociation in the docs as well.

Query on associated value in sails

There are two tables, Books which has many-to-many association with Tags.
How can the Book that have only particular tag id be found?
I tried:
Book.find().populate("tag", where:{id: 1 }).exec(console.log)
But it gives all the books.
If your looking for all books with a specific tagid, your going to want to do something like:
Tag
.findOne(1)
.populate('books')
.then(function(tag) {
if (!tag) {
res.serverError(error);
} else {
res.json(tag.books);
}
});
Basically you want to look up the tag by id (1), and then populate the books association for that tag.
You must provide criteria in find(), not in populate.
Your fixed variant:
Book
.find()
.where({
id: 1
})
.populate('tag')
.exec(function(error, books) {
if (error) {
res.serverError(error);
} else {
res.json(books);
}
});