referring to JSON key with out using specific name - json

lets say I have a JSON/object literal like so:
var animals = {
dogs : {
breed : 'breed name'
weight : 'fat'
},
cats : {
breed : 'breed name'
weight : 'fat'
}
}
because dogs and cats are the same, is there a way to abstract that key? So for example if you were doing a loop on animals, how would you have a single loop and get to breed and weight of dogs and cats with out actually using dogs and cats? The JSON I have goes a couple levels deeper than this before this happens.
Thanks for any help!

Yes it is possible. You can loop over the keys of the object.
for(var animalName in animals) {
currentAnimal=animals[animalName];
console.log(animalName,currentAnimal);
}
That will loop through all your animals and print the name and the associated object.
Just FYI: Your JSON is invalid, you need to add commas between the properties

Related

Is there anyway to match name and number?

For each client we have, we associate their name with an ID number in a database. However, we sign people in by name. I am trying to convert the names into their ID number in a spreadsheet.
I have a list of all the names and corresponding IDs. I realize that I could hard code it so that it would look something like:
for (i=0; i < 31; i++) {
if name = 'john doe'
id = 256589
elseif name = 'jane doe'
id = 248352...}
and repeat that for each client. I've tested with a couple names and this solution does work. Since we don't have that many individuals come in it wouldn't be impossible to just repeat it. However, I would like to know if there are any shortcuts available.
It depends where you're doing this lookup.
This looks like script so you could use an object with the names as keys:
function getIdFromName(name) {
// list of all employees and ids
let employees = {
"john doe": 256589,
"jane doe": 248352
}
if (employees[name]) {
return employees[name]
} else {
// this covers the case if name not found
return false
}
}
// in rest of your code
var id = getIdFromName(name)
If you want to do the lookup in the sheet, you can use a lookup table containing names and ids then use VLOOKUP/INDEX(MATCH()) to find the corresponding ID

Schema from nested JSON list

I have a JSON list which captures one to many relationships.
For example, School can have multiple Class objects and Class can have multiple Student objects, but Student only belongs to one Class and one School:
{
"School": [ {
"id": 1,
"name": "Grad School",
"Class": [ {
"name": 101,
"Student": [ {
"name": 501,
"propertyA": "test"
}]
}]
}]
}
I am trying to convert this JSON example into an appropriate schema but the nesting is causing issues. Apollo appears to be able to help but the example below isn't very descriptive:
https://launchpad.graphql.com/4nqqqmr19
I'm looking for suggestions on how to handle this situation, whether that be through a JSON schema converter (which handles nested situations) or other.
I think you issue is not really the schema, which to me looks straightforward:
You have these types (everything dummy code as you have not specified in what language/framework you want to provide the GraphQL-Api):
SchoolType
id ID
name String
classes [Class]
students [Students]
ClassType
id ID
name String
school School
students [Student]
StudentType
id ID
name String
class Class
school School
Then we need an entry point
classQueryType
name "school"
argument :id, ID
resolve do
schools.where(id: argument["id"])
So we have the schema. The bigger work is probably to get the different types to access the JSON Schema in a way that the types above work.
So let's say, we read the JSON data somehow, with the structure you have.
const DATA = JSON.parse("your-example.json")
We need to convert this into different collections of objects, so we can query them dynamically:
schools = []
classes = []
people = []
def build_schools(data)
data.schools.for_each do |school|
schools.push(
name: school.name,
id: school.id,
classes: build_classes(school)
)
end
end
def build_classes(school)
ids = []
school.classes.for_each do |class|
ids.push(class.id)
classes.push(
id: class.id
name: class.name
school_id: school.id # you create your own references, to associate these objects
students: build_students(class)
)
end
return ids
end
...
But then you still need to hook this up, with your type system. Which means to write your resolvers:
For example on the StudentType
StudentType
id ID
name String
class Class
school School
resolve(object) ->
school_id = students.where(id: object.id).class_id.school_id
schools.where(id: school_id)

How to access individual values of a struct?

I'm trying to print the individual members of Results after parsing JSON data and assigning it to Question.
struct Question: Decodable
{
let response_code: Int
let results: [Results]
}
struct Results: Decodable
{
let category: String
let question: String
let correct_answer: String
let incorrect_answers: [String]
}
I tried using:
print(question.results)
But I get:
[Trivia_Game.Results(category: "Entertainment: Music", question: "Which of the following bands is Tom DeLonge not a part of?", correct_answer: "+44", incorrect_answers: ["Box Car Racer", "Blink-182", "Angels & Airwaves"])]
How do I access the individual members such as "category" or "question"?
You would have to first access an individual element of question.results, like so:
question.results[n] // where n represents a valid array index number
And then to access specific properties of that individual Results structure, you would do it in the same way as you would access the value of a property of any other struct. For example, if you wanted to get the value of the category member of a Results structure, you would do this:
question.results[n].category
And then if you wanted to print the value of that specific member (again, using the category member as an example), you would do this:
print(question.results[n].category)
Now, if you wanted to print out the value of the category member for each of the Results structures in the question.results array, then you could use a for loop like so:
for result in question.results {
print(result.category)
}
Hope that helps.
results is an array. You have to enumerate the array
let results = question.results
for result in results {
print(result.category, result.question)
}
or
question.results.forEach { print($0.category, $0.question) }

CouchbaseLite Inverse Relationship not working

I tried putting this off for as long as I could, but I'm really stuck here.
I'm trying to utilize Inverse Relationships
Basically my scheme looks like this:
class Album
var artist: artist?
class Artist
#NSManaged var albums:NSArray?
class func albumsInverseRelation() -> String { return "artist" }
class func albumsItemClass() -> AnyClass { return Album.self }
Then later I try to access the computed property, albums
bgdb.modelFactory?.registerClass("Album", forDocumentType: "Album")
bgdb.modelFactory?.registerClass("Artist", forDocumentType: "Artist")
if let artistID = artist?.document?.documentID, let fetchedArtist = try! Artist.fetchOne(field: "_id", operand: .Matches, value: artistID as AnyObject, database: bgdb) {
print(fetchedArtist.albums as! [Album])
}
But fetchedArtist.albums returns an empty array!
This is why I'm confused, from debugging:
(lldb) po album?.artist?.document?.documentID
▿ Optional<String>
- some : "-obO5dJTBF-xu4lzbWTM9yU"
(lldb) po fetchedArtist.document?.documentID
▿ Optional<String>
- some : "-obO5dJTBF-xu4lzbWTM9yU"
As it appears, there is an Album that has an Artist ID
and I can also match that Artist ID with an existing Artist
Yet when I ask the artist instance for it's albums, it fails to return the Album that has the same artist ID
Am I missing something here?
Sweet baby ...
Biggest waste of a few hours I've had in a while
in my code where I was setting the artist property
albumInstance.artist = artistInstance
it set the model, and everything seemed fine...
But I wasn't calling
albumInstance.save() right after...
So at runtime, I could see that albumInstance.artist had the right document ID, but without save(), the inverse relationship can't work.
yeah... doing that fixed everything...

Groupby array by multiple values

I have an array I want to use groupby angular's filter and to group it by an array of criterias. Is there any way to do this? I guess I might use revision but I don't know how.
For example I have array of football teams. Each team have color, number of players, name, city, country.
I have array of data filters -country, city, players and color and I want to use groupby in the order of this array
not sure about angular. but just include underscore (it's more known for array/object manipulation) into your project then:
say you had an array of objects like an array of these:
car = {
make: "nissan",
model: "sunny",
color: "red"
};
then you'd just go:
var redCars = _.groupBy(cars, 'color');