I have the below JSON and in each object there is an artist and image values. I want a mechanism that when I give a name of the artist it returns the value of the image in the same object. All objects are warped in an array as a JSON.
var iTunes_data = $([{
"title": "title1",
"image": "images/image1.jpg"
},
{
"title": "Hotel California [Rainwave Chiptunes]",
"image": "images/image2.jpg"
},
{
"title": "The Multi-Story Car Park [Rainwave Chiptunes]",
"image": "images/image3.jpg"
},
{
"title": "title4",
"image": "images/image4.jpg"
},
{
"title": "title5",
"image": "images/image2.jpg"
}
]);
function getImage(currentTitle) {
let url = iTunes_data.filter(element => element.title === currentTitle);
return url[0].image;
}
console.log(getImage("title5"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So when I ask for title5 I want to get images/image2.jpg.
I do not want to use the any loop. It has to be more by finding the key and getting the value rather than going through the JSON by a loop, as I find this way faster.
Any idea how to make it working?
Thanks in advance
There's no way to not use a loop. If you want to be more efficient you should take an imperative approach with a for loop and break with a match.
for(let obj in data) {
if(obj.title === title)
// match
break
}
Hope this helps.
To get a specific element from an array without looping, you'll have to know its index. The best you could do is to only loop the array once to map each title to the element's index in the array, here is an example:
const arr = [{
"title": "title1",
"image": "images/image1.jpg"
},
{
"title": "Hotel California [Rainwave Chiptunes]",
"image": "images/image2.jpg"
},
{
"title": "The Multi-Story Car Park [Rainwave Chiptunes]",
"image": "images/image3.jpg"
},
{
"title": "title4",
"image": "images/image4.jpg"
},
{
"title": "title5",
"image": "images/image2.jpg"
}]
const map = arr.reduce((a, c, index) => {
a[c.title] = index;
return a;
},{});
function getImage(title) {
if (!isNaN(map[title])) {
return arr[map[title]].image;
}
}
console.log(getImage('title5'));
I've used a normal array instead of a jQuery object in this example.
I'm assuming the array will not change, you'll have to keep the map in sync if you're going to change the array's content.
Related
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.
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
This question already has answers here:
Finding matching objects in an array of objects?
(5 answers)
Closed 8 years ago.
Say I have a JSON array containing an bunch of different key/values per each object. I know how to use Javascript to target a specific key/value, but what if I want to search through the entire JSON file to find an item, and then also find a related pair within that same object.
For example, how would I scan the following JSON for "Moby Dick", but then also find the author that is tied to that title?
"store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
}
}
Assuming this is your object:
var store= {
"book": [
{...}, {...}
]
}
Then you can try to filter it like this:
var foundBooks = store.book.filter(function(book) { return book.title ==="Moby Dick"});
As correctly pointed out for #JLRiche foundBooks is an array. In order to access the first match it will be in the same way we do with all arrays:
var book = foundBooks[0];
You'd have to iterate the list, you can create some custom functions, like so:
function findTitle(title) {
for (var i = 0; i < data.store.book.length; i++) {
if (data.store.book[i].title == title) {
return data.store.book[i];
}
}
}
So you can do:
var book = findTitle("Moby Dick"),
author = book.author;
You would loop through your book objects and find where book.title === "Moby Dick" and then take a look at book.author for that particular object.
I'm working with a jsonp object, it lists items like this:
{
"played_tracks": [
{
"artist": {
"id": 5524,
"name": "BAAUER",
}
},
"title": "Harlem Shake",
},
{
"artist": {
"id": 114,
"name": "BIRDY",
}
},
"title": "Wings ",
},
{
"artist": {
"id": 1257,
"name": "MILEY CYRUS",
}
},
"title": "Wrecking Ball",
},
{
etc........
Now currently I'm using this code to loop through all of them:
for(i in json.played_tracks)
{
oTrack = json.played_tracks[i];
etc.........
}
How do I adjust my code to only display the last played song? The last song is the first item in the jSONP object.
Instead of looping over json.playedTracks, just fetch the first item of the array like so:
oTrack = json.playedTracks[0];
As you say, the first item is the "last played track," so that should do what you want. If you need the other end of the list though, you can grab that element just as easily:
oTrack = json.playedTracks[json.playedTracks.length - 1];
I know there's plenty of answers on this and most are suggesting looping thru the object, returning what you need, I'm not sure this is the best approach, in my case anyway.
What I have is array with entries referencing to another array people(with id and name) by person_id and projects(with id and name) by project_id.
What I need is to be able to access project and person with a particular id inside the loop on entries, so I can get their names. Doing what others have suggested I'd loop thru people and projects inside each irritation of entries, which seems like awful lot of looping.
So I thought I'd make something I called a "hashtable" from both people and projects on init, which means pretty much creating a new objects people_hashtable and projects_hashtable where key would be the id
so
[
{
"id": "8",
"name": "John Doe"
}
]
would became
{
"8": {
"name": "John Doe"
}
}
this way I'd have easy access to the name without looping all the time while still maintaining the old array with its original order(that's why I'm not outputting it this way directly from server, you can't quite order an object and I'm using both people and projects in a selectbox, which needs to be ordered by name).
Am I doing it right? Are there better way? Or should I forget this completely and stick with the search loop as suggested in other question?
I'm trying to be as efficient as possible on both server and client side.
You basically doubled all the objects just to avoid loop. So, unless you have some bad performance issues, I would avoid that.
In case you really, really need a kind of hashmap, I would prefer storing the array's index instead of another copy of the object:
// array
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
// lookup table
var lookup = {
"8": 0
}
Of course doing that, means you can't modifying the array's without rebuild the hashmap.
Generate it's quite simple:
var lookup = arr.reduce(function(lookup, item, index) {
lookup[item.id] = index;
return lookup;
}, {});
You can also use that to generate the object you mentioned your question:
var lookup = arr.reduce(function(lookup, item) {
lookup[item.id] = {name: item.name};
return lookup;
}, {});
But as I said it's something I would avoid.
Following code may help you. JSFIDDLE
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
var obj = {};
for(var i=0; i< arr.length; i++){
obj[arr[i].id] = {name: arr[i].name};
}
console.log(obj);
var articles= {
"item1":{
"id":"155",
"name":"First Item",
"value":-5199.6
},
"item2":{
"id":"255",
"name":"Second Item",
"value":-424.91
}
}
var ids = [];
for(var item in articles) {
ids.push(articles[item]['id']);
}
console.log(ids);
This lib https://github.com/paularmstrong/normalizr makes it pretty easy to do. Both normalization and denormalization.
It can turn this
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
into this
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
and the other way around.