Getting first item in jsonp object - javascript

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];

Related

How to find the value of a key in JSON

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.

Nested forEach issue

I have two arrays of object, the first array (printers, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
cartridges: [],
},
....
]
The second array (cardridges, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "ECH"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do first is to is to iterate through the first array and and then iterate for all the cardridge available: if a the value customData.brand.value of a cardridge is included inside the array 'compatibility' of a printer, then I have to add this cardridge object inside the cardridges array of this printer. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
printers.forEach((printerItem) => {
const printer = printerItem;
printer.compatibilty.forEach((compatibilityItem) => {
const compatibility = compatibilityItem;
cardridges.forEach((cartridge) => {
if (compatibility === cartridge.customData.brand.value.content) {
printer.cartridges.push(cartridge);
}
});
});
});
What am I doing wrong?
You're accessing the wrong property. It should be cartridge.customData.brandName.value.content, carefully note brandName.value rather than brand.value
Your issue is that you're accessing it by the wrong property - brand and not brandName.
Furthermore, if you're targeting everything but IE, you could simplify your nested for loops to utilize some fancy ES6 array methods.
printers.forEach((p) => {
p.cartridges.push(cartridges.filter((c) => {
const brandName = c.customData.brandName.value.content;
return p.compatibilty.includes(brandName);
}));
});

Meteor Import JSON into Collection

I am trying to import a JSON file that has embedded objects into the MongoDB and would like to know how to format to import the doc correctly. To be clear the doc format must remain in its current form. I must modify/create a function or method that would allow this file to be imported with _id associated in the sport-events array loop (Ive shorted to one sports-event array for brevity). Perhaps a better way of putting the question is how could I import eveything in the sports-event array and leave the rest of the doc.
JSON Doc.
{
"sports-content": {
"sport-event": [{
"event-metadata": {
"league": "NCAA Basketball",
"event-type": "0",
"league-details": "NCAAB",
"event-date-time": "12/18/2015 07:00 PM",
"eventNum": "3000460",
"status": "",
"off-the-board": "False"
},
"team": [{
"team-metadata": {
"alignment": "Home",
"nss": "526",
"openNum": "526",
"name": {
"full": "Clemson"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}, {
"team-metadata": {
"alignment": "Away",
"openNum": "525",
"nss": "525",
"name": {
"full": "South Carolina"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "-1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}]
}],
"sports-meta-data": {
"doc-time": "42353.5979256944"
}
}
}
Meteor server.js under Meteor.startup
if (SportEventsFeed.find().count() === 0) {
console.log("Importing private/products.json to db")
var data = JSON.parse(Assets.getText("ncaab.json"));
data.forEach(function (item, index, array) {
SportEventsFeed.insert(item);
})
}
Here is how you can just insert the items from the 'sports-event' array as individual documents in the db.
I'm not sure if the index value is what you wanted for the _id field, if not change the value assigned to item_id (or comment out this line for a default _id).
if (SportEventsFeed.find().count() === 0) {
console.log("Importing private/products.json to db")
var data = JSON.parse(Assets.getText("ncaab.json"));
data['sports-content']['sports-event'].forEach(function (item, index, array) {
item._id = index;
SportEventsFeed.insert(item);
})
}

Simple json reading the api

I have a query that produces the following results:
{
"data": [
{
"id": "1107702400"
},
{
"id": "1149862205",
"likes": {
"data": [
{
"name": "Penelope Test",
"category": "Arts/entertainment/nightlife",
"id": "411133928921438",
"created_time": "2012-05-23T11:41:27+0000"
},
The first id I can access through:
response.data[i].id
How do I retrieve the second id? (the one that goes data-id-data-id ?)
I have this function:
for(i=0;i<response.data.length;i++)
{
testdiv.innerHTML += response.data.data[i].id + '<br/>' ;
}
Which lets me print the first id.
What do I need to do in order to print the second id?
In your example data
response.data[i].likes.data[0].id

How to create JSON using Javascript with sets of data?

I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal
You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.

Categories