Javascript gets undefined on array - javascript

I have the following data structure for javascript:
var data = {
"announcements": {
"IFT4S": [{
"id": "D7214",
"read_state": "unread",
"posted_at": "2018-10-25T14:35:54Z",
"title": "Reminder! Systems disruption: 27-28 Oct",
"message": "All University online systems will be unavailable."
}, {
"id": "B399C",
"read_state": "read",
"posted_at": "2018-10-22T09:04:48Z",
"title": "Stem Fair",
"message": "The STEM Careers Fair is taking place on 31 October 2018"
}, {
"id": "6F5EE",
"read_state": "unread",
"posted_at": "2018-10-22T09:04:48Z",
"title": "Smile more, worry less with our FREE course",
"message": "Take part in our Online Mindfulness Programme."
}]
}
}
I want to access the values of the keys "read_state", "posted_at", "title" and "message".
However, when I try data.announcements.IFT4S["title"] or any other key instead of "title" I get the undefined in the console.
What am I doing wrong?

when I try data.announcements.IFT4S["title"] or any other key instead
of "title" I get the undefined in the console. What am I doing wrong?
What you are doing here is trying to access the title key of the IFT4S array.
The issue is that IFT4S doesn't have a title key. Instead, like an array object, it has indexes as keys.
IFT4S = [ {...}, {...}, {...} ]
To access the first element of the IFT4S array you would do it like this
IFT4S[0]
In your case that would return the object at the first position of IFT4S array (index 0)
{
id: "D7214",
read_state: "unread",
posted_at: "2018-10-25T14:35:54Z",
title: "Reminder! Systems disruption: 27-28 Oct",
message: "All University online systems will be unavailable."
}
If you want to get all the titles from all the elements inside IFT4S array you could do this
IFT4S.map(element => element.title)
Array.prototype.map returns a new array where each element is the result of applying the function specified inside map to each element of the original array.
In this case, it would return
[
"Reminder! Systems disruption: 27-28 Oct",
"Stem Fair",
"Smile more, worry less with our FREE course"
]

You have to itrate over the array to get value from an array of object
var data = {
"announcements": {
"IFT4S": [
{
"id": "D7214",
"read_state": "unread",
"posted_at": "2018-10-25T14:35:54Z",
"title": "Reminder! Systems disruption: 27-28 Oct",
"message": "All University online systems will be unavailable."
},
{
"id": "B399C",
"read_state": "read",
"posted_at": "2018-10-22T09:04:48Z",
"title": "Stem Fair",
"message": "The STEM Careers Fair is taking place on 31 October 2018"
},
{
"id": "6F5EE",
"read_state": "unread",
"posted_at": "2018-10-22T09:04:48Z",
"title": "Smile more, worry less with our FREE course",
"message": "Take part in our Online Mindfulness Programme."
},
]
}
}
data.announcements.IFT4S.forEach(item => {
console.log(item.title)
})
or you can do like this,
0 is the index
console.log(data.announcements.IFT4S[0].read_state)
console.log(data.announcements.IFT4S[0].title)

IFT4S is an array, you can access its objects and their values values by calling:
data.announcements.IFT4S[index].title
with index beeing one of 0-2 here since the array contains 3 objects.
For example:
data.announcements.IFT4S[0].title
This is a very basic concept, check out any javascript guide to learn about arrays.

Related

I have a JSON file with data property which contains objects that contain information about champions. How to get champion with specific KEY property?

I have a huge static JSON file that contains all champions in a certain game and some information about them. Currently, I need to figure out how to find the champion object whose "key" property is 266. Sadly I'm having some difficulty figuring out how to get that object. I assume I have to loop through the objects, however, usually when I loop through something, it's an array but this is not the case.
I've put a simplified example of the json structure below. I have an integer 266 and now I need to somehow access the object with "key": "266" which would be Aatrox. Any clues on how would I do that?
"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
You can use find
Get the entries from data key using Object.entries
Find value whose key property is equal to our desired key using find
let obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
let findByKey = (matchKey) => Object.entries(obj.data).find(([key,value]) => value.key === matchKey)
console.log(findByKey('266'))
Here's a generic function you can use to search for any key and value:
const obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
const searchKeyValue = {key:"key", value:"266"}
const search = data => skv => Object.entries(data).filter(([key,value])=>value[skv.key]===skv.value)
console.log(search(obj.data)(searchKeyValue))
So you can find via e.g. searchKeyValue = {key:"id", value:"Ahri"} or whatever you like.
You could also use JSONPath i.e.
$..data[?(#.key==266)]
Assuming :
{"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
}

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Check if any value in jsonPath is repeated

I have a jsonPath as below
{ "book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Nigel Rees",
"title": "Sword of Honour",
"price": 12.99
}
]}
And Want to check if any author name have got repeated?
I tried
$.book[?(#.author=='Nigel Rees')].find(1)
But, it always throws an exception that found nothing, how could I check that the author='Nigel Rees' occurrences i.e author='Nigel Rees' have a two books?
Depends what you are planning on doing if the authors names exists.
If you only want the objects with author of Nigel Reese you could use a filter.
var booksByNigelReese = book.filter( function(book, index) {
return book.author === 'Nigel Reese'
})
.filter() takes a function that takes the book and index, chooes to accept or rejcet the book into a new array depending if the result of the function is true or false

How to loop through array of objects in Node/Express and check if a match exists in MongoDB database?

I am building a web app with the MEAN stack and Yelp API that returns an array of objects, where each object is a local business. I work with this data in the front-end, but before I send a response I want to check if a particular object exists in the MongoDB database and I am struggling with how to do that.
Here is an object that is returned from the API:
[
{
"name": "Arendsnest",
"url": "https://www.yelp.com/biz/arendsnest-amsterdam-2?adjust_creative=ycRBsh7KEkNFq3wJvKoL6Q&utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=ycRBsh7KEkNFq3wJvKoL6Q",
"snippet_text": "The reigning Lord of Amsterdam beer bars. Popular and seats go fast...come early. Ask for the massive all-Dutch beer list and prepare to have your...",
"image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/FurcfTuqaYBv_q34bGTK5g/ms.jpg"
},
{
"name": "Bar Oldenhof",
"url": "https://www.yelp.com/biz/bar-oldenhof-amsterdam?adjust_creative=ycRBsh7KEkNFq3wJvKoL6Q&utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=ycRBsh7KEkNFq3wJvKoL6Q",
"snippet_text": "So I'm not much of a drinker. My taste is highly selective and I usually prefer not to drink alcohol altogether. But my husband is the opposite so on a...",
"image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/1k57z7ziIW8MyAWHlXWGdg/ms.jpg"
},
{
"name": "Beer Temple",
"url": "https://www.yelp.com/biz/beer-temple-amsterdam?adjust_creative=ycRBsh7KEkNFq3wJvKoL6Q&utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=ycRBsh7KEkNFq3wJvKoL6Q",
"snippet_text": "This is a great place to stop in and have some American craft beer. With 30+ taps and a seemingly never ending list of bottle selections, you have many...",
"image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/yxUiYre1Y6ULqMhQ30NPOA/ms.jpg"
},
{
"name": "Tales & Spirits",
"url": "https://www.yelp.com/biz/tales-en-spirits-amsterdam?adjust_creative=ycRBsh7KEkNFq3wJvKoL6Q&utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=ycRBsh7KEkNFq3wJvKoL6Q",
"snippet_text": "This is exactly what every high-end cocktail bar should strive to have and be.\n\nFriendly staff: From the bartenders to the manager to the waitress. Everyone...",
"image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/IElXytpbY0bpp7ZdjFdGvA/ms.jpg"
}
]
This exists in the MongoDB database:
{
"_id": {
"$oid": "57da26d8dcba0f51172f47b1"
},
"name": "Arendsnest",
"url": "https://www.yelp.com/biz/arendsnest-amsterdam-2?adjust_creative=ycRBsh7KEkNFq3wJvKoL6Q&utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=ycRBsh7KEkNFq3wJvKoL6Q",
"snippet_text": "The reigning Lord of Amsterdam beer bars. Popular and seats go fast...come early. Ask for the massive all-Dutch beer list and prepare to have your...",
"image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/FurcfTuqaYBv_q34bGTK5g/ms.jpg"
}
How can I write a query in Node to loop through my array using name property and do a check on every object if it exists in the database and return the data?
No need to iterate the array, use the $or operator with a mapped array that has the fields you want to query.
Take the following example where you want to search for a match of two properties:
var yelp = [
{
"name": "Arendsnest",
"url": "url1",
"snippet_text": "foo",
"image_url": "bar.jpg"
},
{
"name": "Bar Oldenhof",
"url": "abc",
"snippet_text": "efg",
"image_url": "ms.jpg"
},
{
"name": "Beer Temple",
"url": "https://www.yelp.com/",
"snippet_text": "test",
"image_url": "ms.jpg"
},
{
"name": "Tales & Spirits",
"url": "https://www.yelp.com/",
"snippet_text": "This is exactly...",
"image_url": "ms.jpg"
}
],
query = yelp.map(function(item){ return { name: item.name, url: item.url }; });
db.collection.find({ "$or": query });
This will create an array that you can use as the $or expression in your find() method, equivalent to :
db.collection.find({
"$or": [
{
"name": "Arendsnest",
"url": "url1"
},
{
"name": "Bar Oldenhof",
"url": "abc"
},
{
"name": "Beer Temple",
"url": "https://www.yelp.com/"
},
{
"name": "Tales & Spirits",
"url": "https://www.yelp.com/"
}
]
})
For querying on single properties, say for instance you want to query on just the name field, better use the $in operator which is better optimised for such:
query = yelp.map(function(item){ return item.name; });
db.collection.find({ "name": { "$in": query } });

Backbone.js design pattern for JSON data

I've got a question about best practice when designing JSON file which will be displayed by Backbone.js. I know that Backbone is completly agnostic in this topic, but maybe someone will give me good advice in this certain situation.
In the end, I need to have some views which will look like this
On 4th of July, in _____ we calebrate ____ day.
___ means a gap in text, where I'll have an text input or select (depends on type) which correctness will be verified.
So, I need to have a JSON file that describes that piece of text.
I thought about something like this
"body": [
{
"preInputText": "On 4th of July, in ",
"postInputText": "",
"answersID": ["1", "2"]
},
{
"preInputText": "we calebrate ",
"postInputText": " day",
"answersID": ["3"]
}
]
"answers": [
{
"ID": "1",
"content": "USA",
"correct": true
},
{
"ID": "2",
"content": "Canada",
"correct": false
},
{
"ID": "3",
"content": "Independent",
"correct": true
}
]
or, maybe simpleier, but not-so-flat
"body": [
{
"preInputText": "On 4th of July, in ",
"postInputText": "",
"answers": [
{
"ID": "1",
"content": "USA",
"correct": true
},
{
"ID": "2",
"content": "Canada",
"correct": false
},
]
}
]
etc…
So, first approach enforce creating two collections, passing them into one view, and checking values beetween them.
The second, just one collection of models that contains both body and answers, but parsing them at initialization and using nested construction.
I don't know is it a bad pratice (to use nested models), but as i read backbone was designed to think in the more flat way.
Maybe there is some kind of another logic? What do you think?
Thanks!
I'm more with the first approach (the flat one) and I don't agree with you that it enforce creating two collections.
You can always create a single collection and override it's parse function, something like this :
var MyCollection = Backbone.Collection.extend({
...
parse: function(resp) {
this.answers = new Backbone.Collection(resp.answers);
return resp.body;
}
});
...
// myCollection is an instance of MyCollection
myCollection.models // refer to questions
myCollection.answers // refer to answers
"body": [
{
"preInputText": "On 4th of July, in ",
"postInputText": "",
"answers" [ { "ID": "1", "content": "USA", "correct": "true"},
{ "ID": "1", "content": "canada", "correct": "false"}
]
},
{
"preInputText": "we calebrate ",
"postInputText": " day",
"answersID": [{ "ID": "3", "content": "Independent", "correct": "true"},
]
}
]
Using this structure, you need to use one collection. Then you can treat each object in this as a model and you can render these using their separate views in a collection view. So need to use nested models here

Categories