How to Call Array Through API and Push to New Array - javascript

I am trying to figure out the proper syntax to push a set of array values to a new array after making an API call. I am trying to combine 2 paths from one API call into a single array to use for an image slider for a product page on an eCommerce site. Here's what I have so far. I need help with the second path and push to array. Any input would be appreciated!
JavaScript
$.getJSON("item-data.json", function(results) {
$.each(results.CatalogEntryView, function(index, item) {
var slideshowArray = [];
//the first path - this works
slideshowArray.push(item.Images[0].PrimaryImage[0].image)
//the second path
$.each(item.Images[0].AlternateImages[0].image, function(k, v) {
slideshowArray.push(v);
});
//used to verify the successful array push
console.log(slideshowArray.length);
});
});
JSON
{
"CatalogEntryView": [
{
"CustomerReview": [
{
"Con": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "4"
},
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"datePosted": "Mon Mar 11 13:13:55 UTC 2013",
"overallRating": "1",
"review": "Less than 2 months after purchase it completely stopped working. First it wouldn't detect the pitcher when trying to blend a significant amount, a couple weeks later it wouldn't detect the single serve cup. ",
"reviewKey": "b326b0d6-e6ae-4ec5-8080-720f0ad741af",
"screenName": "New York",
"title": "Very unhappy"
}
],
"ConsolidatedRatableAttributes": [
{
"description": "Quality",
"name": "QUALITY",
"value": "4"
},
{
"description": "Easy to Use",
"name": "EASY_TO_USE",
"value": "4.5"
},
{
"description": "Value",
"name": "VALUE",
"value": "3.5"
}
],
"Pro": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"datePosted": "Thu Apr 18 19:42:19 UTC 2013",
"overallRating": "5",
"review": "This blender works amazingly, and blends within seconds. The single serve cups also work really well for smoothies or protein shakes!",
"reviewKey": "d602bcdf-53be-4769-94da-3b3fd2517d21",
"screenName": "Eric",
"title": "Fantastic Blender"
}
],
"Reviews": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "4"
},
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"city": "NYC",
"customerId": "110657105",
"datePosted": "Mon Mar 11 13:13:55 UTC 2013",
"helpfulVotes": "39",
"overallRating": "1",
"review": "Less than 2 months after purchase it completely stopped working. First it wouldn't detect the pitcher when trying to blend a significant amount, a couple weeks later it wouldn't detect the single serve cup. ",
"reviewKey": "b326b0d6-e6ae-4ec5-8080-720f0ad741af",
"screenName": "New York",
"state": "NY",
"title": "Very unhappy",
"totalComments": "0",
"totalVotes": "52"
},
{
"Comments": [
{
"city": "",
"commentKey": "CommentKey:ffcefb66-381a-4985-b869-9fcfdd26e7cc",
"commentText": "Separating the men from the boys, separating the amateurs from the professionals when it comes to blenders, when you revealed to us that, -It doesn't pulverize seeds-.I really need a good blender, but there is No way that I would buy this blender now. Thank you so much, Jon",
"postedDate": "Thu Oct 10 04:17:50 UTC 2013",
"screenName": "JON",
"userKey": "118863321",
"userTier": "Trusted"
}
],
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "2"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "3"
},
{
"description": "value",
"name": "VALUE",
"value": "2"
}
],
"city": "Idaho Falls",
"customerId": "116317693",
"datePosted": "Sun Sep 01 03:18:11 UTC 2013",
"helpfulVotes": "16",
"overallRating": "2",
"review": "This blender is not superior to other smoothie blenders, It doesn't pulverize seeds and leaves green smoothies chunky with a lot of pulp. The single serve concept is amazing, however, my single serve cup began to break right from the start. The prongs became chipped because of the difficulty of screwing it in and out of the base. It won't blend for more than a minute without smelling like burned rubber. While the single serve seemed to blend more smoothly, it didn't hold much, especially when adding ice. I was very disappointed and so I returned it,",
"reviewKey": "399853f3-4451-40a8-bcd6-bda2d814d9f4",
"screenName": "London",
"state": "ID",
"title": "Very Disappointed",
"totalComments": "1",
"totalVotes": "21"
},
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Oakland",
"customerId": "100025104",
"datePosted": "Thu Apr 18 19:42:19 UTC 2013",
"helpfulVotes": "10",
"overallRating": "5",
"review": "This blender works amazingly, and blends within seconds. The single serve cups also work really well for smoothies or protein shakes!",
"reviewKey": "d602bcdf-53be-4769-94da-3b3fd2517d21",
"screenName": "Eric",
"state": "CA",
"title": "Fantastic Blender",
"totalComments": "0",
"totalVotes": "10"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Cambridge",
"customerId": "172227",
"datePosted": "Sat Jan 18 01:20:36 UTC 2014",
"helpfulVotes": "9",
"overallRating": "5",
"review": "I am blown away by this blender. It obliterates ice and frozen fruit - and blends fresh fruits to smooth perfection. It even makes quick work of fresh ginger and tough greens. I did a ton of research before settling on the Ninja. This was a splurge for me - and I spent the extra money to get the single serve cups, thinking I'd take my smoothie to work every morning. But my husband is totally hooked on smoothies now too, so the big pitcher is getting regular use. Tried it out for margaritas tonight... half a lime, half a lemon, half an orange with tequila, honey and ice... unbelievably good. Haven't tried it for soup or sauce yet, but can hardly wait.\n\nI'm impressed by features such as the suction cup feet, the snap-seal lid, and the sensor that prevents the machine from being turned on without the top in place. It cleans up nicely too. \n\nBottom line: I can't stop raving about this thing and have recommended it to all my friends and family.",
"reviewKey": "d8e9ac59-6c3a-47be-8b87-f912715ccd18",
"screenName": "E",
"state": "MA",
"title": "Couldn't be happier",
"totalComments": "0",
"totalVotes": "9"
},
{
"Comments": [
{
"city": "",
"commentKey": "CommentKey:a5b92fc8-ec2a-4772-b4ea-3cf4d473015b",
"commentText": "THANK YOU, THANK YOU!!!!! YOU JUST GAVE ME THE BEST REASON TO -- NOT BUY -- THIS THING ! THANK YOU, JON",
"postedDate": "Thu Oct 10 03:44:47 UTC 2013",
"screenName": "JON",
"userKey": "118863321",
"userTier": "Trusted"
}
],
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"city": "new york",
"customerId": "116426870",
"datePosted": "Thu Jun 06 04:49:37 UTC 2013",
"helpfulVotes": "38",
"overallRating": "1",
"review": " Upon using this blender it turns out that the food gets into a deep hole at the bottom of the blade assembly , which fits on top of the rotating spindle, which cannot be cleaned. No amount of rinsing or dish washer washing can get to it. A special thin and long brush would be required. Such food deposits can quickly become a place for bacteria growth and accumulate soap from dishwasher etc. A radical design change and going back to the drawing board is required, which Ninja would be unwilling to do. Very poor and harmful product",
"reviewKey": "49add669-1256-4894-9fce-9e0464342887",
"screenName": "gourmet",
"state": "NY",
"title": "bacteria hazard",
"totalComments": "1",
"totalVotes": "69"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Wilmington ",
"customerId": "115016455",
"datePosted": "Sun Mar 16 13:54:36 UTC 2014",
"helpfulVotes": "5",
"overallRating": "5",
"review": "Right out of the box I love this thing. You have to read the instructions: it indicates you must pulse several times THEN blend in order to get the smooth consistency. I'm going now to google soups to make. I'll add on to my review once I've tried more stuff. I know some folks had problems, I can say with total confidence that Ninja backs up what they make. I have a vacuum, steamer and iron and I broke the vacuum and they still fixed it for free. Easy peasy. Be sure to register your purchase. Peace. ",
"reviewKey": "bf2283a9-37a1-46e2-b9b4-3edb757d5375",
"screenName": "Sandra",
"state": "DE",
"title": "Great Blender",
"totalComments": "0",
"totalVotes": "5"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Tucson",
"customerId": "119946555",
"datePosted": "Thu Jan 30 18:50:22 UTC 2014",
"helpfulVotes": "6",
"overallRating": "5",
"review": "My daughter received this Ninja blender and she absolutely loves it. My grandson has Autisim and has very sensitive taste buds. With the Ninja my daughter is able to puree his homemade soups, & refried beans. Life is a little easier for my daughter & him. She is in heaven. \n",
"reviewKey": "7c7ef8c0-e227-45a5-86cd-c29adeb0bd2a",
"screenName": "Flora",
"state": "AZ",
"title": "Ninja Blender",
"totalComments": "0",
"totalVotes": "7"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "4"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Minneapolis",
"customerId": "109690154",
"datePosted": "Sun Jan 12 17:41:43 UTC 2014",
"helpfulVotes": "4",
"overallRating": "5",
"review": "I have to assume that the negative reviewers received an unfortunate "lemon" blender... that, or they didn't read the instruction manual, because I love my Ninja and definitely recommend it.\n\nI've had this blender for over a year and it still works as wonderfully as the day I bought it. I use it primarily for making smoothies, everything from green monsters to peanut butter protein shakes to frozen fruit & yogurt smoothies with chia seeds on top.\n\nIt's like having Jamba Juice in my kitchen, but without the long line of snap-chatting teenagers.\n\nI frequently use the to-go cups to blend and take with me in the car. If you are in the camp lamenting that it doesn't hold enough, you probably also expect that once blended, it will be as full as you originally (over)stuffed it.\n\nRespect the max fill line, people, or use the full-size blender if you are going for NYC Big Gulp size.\n\nI will say, that if you are looking to seriously juice, this is not the blender for you. \n\nIt might take a little experimentation to get the right ratio of liquid to solid\/frozen for a perfectly smooth blend, but once you figure out what works for you, it's easy!",
"reviewKey": "9e0322d2-256e-46a5-80dc-b4468e58359b",
"screenName": "Kari",
"state": "MN",
"title": "Love this blender!",
"totalComments": "0",
"totalVotes": "4"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Houston",
"customerId": "116412794",
"datePosted": "Wed Jun 05 14:26:21 UTC 2013",
"helpfulVotes": "5",
"overallRating": "5",
"review": "[...]\nAll the parts are well made and good quality. The only thing that seems a little flimsy would be the drinking tops for the single serve cups, but those don't even matter because all you are doing is drinking from the tops. All the rest of the machine is top notch.\n\nThis blender is powerful, quiet and very easy to clean. \n\n[...]\nYou will not regret buying this machine. ",
"reviewKey": "4cc67e87-6754-4cab-8eb7-fb3bd738c16c",
"screenName": "Te-Ann",
"state": "TX",
"title": "LOVE LOVE LOVE!!!!",
"totalComments": "0",
"totalVotes": "6"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "4"
}
],
"city": "CENTREVILLE",
"customerId": "102170259",
"datePosted": "Thu Jan 30 05:33:15 UTC 2014",
"helpfulVotes": "3",
"overallRating": "5",
"review": "I'm not sure why there are so many negative reviews about this blender on Target's website, but it's a great blender. The first blender I've own that actually crushes the ice completely! Perfect for shakes!",
"reviewKey": "3e810dba-638f-4146-aee8-190a741d86d5",
"screenName": "SL",
"state": "VA",
"title": "Fantastic blender!!",
"totalComments": "0",
"totalVotes": "3"
}
],
"consolidatedOverallRating": "4",
"totalPages": "2",
"totalReviews": "14"
}
],
"DPCI": "072-04-1840",
"Images": [
{
"AlternateImages": [
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt01"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt02"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt03"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt04"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt05"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt06"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt07"
}
],
"PrimaryImage": [
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758"
}
],
"imageCount": "8",
"source": "internal"
}
],
"ItemDescription": [
{
"features": [
"<strong>Wattage Output:<\/strong> 1100 Watts",
"<strong>Number of Speeds:<\/strong> 3 ",
"<strong>Capacity (volume):<\/strong> 72.0 Oz.",
"<strong>Appliance Capabilities:<\/strong> Blends",
"<strong>Includes:<\/strong> Travel Lid",
"<strong>Material:<\/strong> Plastic",
"<strong>Finish:<\/strong> Painted",
"<strong>Metal Finish:<\/strong> Chrome",
"<strong>Safety and Security Features:<\/strong> Non-Slip Base",
"<strong>Care and Cleaning:<\/strong> Easy-To-Clean, Dishwasher Safe Parts"
]
}
],
"Offers": [
{
"OfferPrice": [
{
"currencyCode": "USD",
"formattedPriceValue": "$139.99",
"priceQualifier": "Online Price",
"priceValue": "13999"
}
]
}
],
"POBoxProhibited": "We regret that this item cannot be shipped to PO Boxes.",
"PackageDimension": [
{
"name": "length",
"unit": "IN",
"value": "17.4"
},
{
"name": "width",
"unit": "IN",
"value": "12.4"
},
{
"name": "height",
"unit": "IN",
"value": "9.9"
},
{
"name": "weight",
"unit": "LB",
"value": "10.85"
}
],
"Promotions": [
{
"Description": [
{
"legalDisclaimer": "Offer available online only. Offer applies to purchases of $50 or more of eligible items across all categories. Look for the "SPEND $50: SHIPS FREE" logo on eligible items. Some exclusions apply. Items that are not eligible are subject to shipping charges. $50 purchase is based on eligible merchandise subtotal. Items that are not eligible, GiftCards, e-GiftCards, gift wrap, tax and shipping and handling charges will not be included in determining merchandise subtotal. Offer valid for orders shipping within the 48 contiguous states, as well as APO\/FPO and for Standard and To the Door shipping methods only. Not valid on previous orders.",
"shortDescription": "SPEND $50, GET FREE SHIPPING"
}
],
"endDate": "2014-05-25 06:59:00.001",
"promotionIdentifier": "10736506",
"promotionType": "Buy catalog entries from category X, get shipping at a fixed price",
"startDate": "2014-05-18 07:00:00.001"
},
{
"Description": [
{
"legalDisclaimer": "Receive a $25 gift card when you buy a Ninja Professional Blender with single serve blending cups or a Ninja MEGA Kitchen System. Not valid on previous orders. On your order summary, the item subtotal will reflect the price of the qualifying item plus the amount of the free gift card, followed by a discount given for the amount of the free gift card. Your price on the order summary will be the price of the qualifying item (the total charges for the qualifying item and gift card). Your account will actually be charged the amount of the qualifying item reduced by the amount of the gift card, and a separate charge for the amount of the gift card. The gift card will be sent to the same address as your order and will ship separately. If you want to return the item you purchased to a Target Store, you may either keep the gift card and just return the qualifying item (you will be refunded the amount of the qualifying item reduced by the amount of the gift card), or you can return the qualifying item and the gift card for a full refund using the online receipt. If you return the item you purchased by mail, keep the gift card; you will be refunded the amount of the qualifying item reduced by the amount of the gift card. Offer expires 05\/24\/14 at 11:59pm PST.",
"shortDescription": "$25 gift card with purchase of a select Ninja Blender"
}
],
"endDate": "2014-05-25 06:59:00.001",
"promotionIdentifier": "10730501",
"promotionType": "Multiple Items Free Gift",
"startDate": "2014-05-11 07:00:00.001"
}
],
"ReturnPolicy": [
{
"ReturnPolicyDetails": [
{
"guestMessage": "View our return policy",
"policyDays": "100",
"user": "Regular Guest"
},
{
"guestMessage": "View our return policy",
"policyDays": "120",
"user": "Best Guest"
}
],
"legalCopy": "refund\/exchange policy<br\/><br\/><p style=\"font-size:13px;\">Most unopened items in new condition returned within 90 days will receive a refund or exchange. Some items have a modified return policy that is less than 90 days. Those items will either show a \"return by\" date or \"return within\" day range under the item on your receipt or packing slip and in the \"Item details, shipping\" tab if purchased on Target.com. Items that are opened or damaged or do not have a packing slip or receipt may be denied a refund or exchange. All bundled items must be returned with all components for a full refund. Bundle components may not all have the same return policy; please check your packing slip for details. Some items, such as gift cards, digital items are never returnable. <br \/><br \/>See the <a href=\"http:\/\/www.target.com\/HelpContent?help=\/sites\/html\/TargetOnline\/help\/returns_and_refunds\/returns_and_refunds.html\">Target return policy<\/a> for complete information.<\/p><br\/>"
}
],
"UPC": "622356532099",
"applyCouponLink": "false",
"buyable": "true",
"callOutMsg": "FREE $25 GIFT CARD",
"catEntryId": "205273068",
"classId": "04",
"department": "072",
"eligibleFor": "ADD_TO_CART",
"inventoryCode": "0",
"inventoryStatus": "Online",
"itemId": "1840",
"itemType": "ItemBean",
"manufacturer": "Euro Pro",
"manufacturerPartNumber": "BL660",
"packageQuantity": "null ",
"partNumber": "14263758",
"purchasingChannel": "Sold Online + in Stores",
"purchasingChannelCode": "0",
"shortDescription": "For the first time EVER - you get the same professional performance power in the Single Serve as well as the XL 72 oz pitcher! The Ninja\u2122 Professional Blender with Single Serve Blending Cups allow you to crush ice into snow, blend whole fruits and vegetables into nutritious beverages, and create resort style blended drinks! Full size blender performance now in individual cups.",
"title": "Ninja\u2122 Professional Blender with Single Serve Blending Cups",
"webclass": "Small Appliances"
}
]
}

Related

What methods do I use to manipulate data of an array within an Object? (Pseudo Code only)

Backstory (skipable):
Hello, I'm a student at Lambda school. Recently we had a JS assessment test in order to progress to the next unit, but I wounded up flunking it twice. So now I have to repeat Unit 1. I'm here today in order to finally knock out that damn exam. I don't have a problem working with Arrays or Objects, what I do have a problem with is figuring out a way to solve issues when they are combined. It's like: "What the hell, do I use map or Object.Key?" Those types of problems appeared throughout the exam. It's fine to challenge students, but I never worked with both at the same time before. The approach was completely lost on me and before I knew it, my 3 hours were up two days straight.
What I hope you can provide:
I'm going to provide one problem and show you the work that I did. What I would like is for you to formulate pseudo code for me to work out that problem. I need to learn how to use Pseudo code if I want to be a good web engineer. Please do not solve the problem for me, all I ask is pseudo code. I'll try to work on the problem based on the pseudo code I feel is manageable for me to do. Thanks in Advance.
Problem and current Status:
/**
* ### Challenge `getSecondStarshipName`
* MVP Challenge 🤓
*
* #instructions
* Return second starship's name from `starships` property.
* If length is 0. Return 'none'
*/
function getSecondStarshipName(character) {
// TODO: Add your code here.
const checkProperty = character.hasOwnProperty("starships");
const checkArray = character.isArray("starships");
const secondShipLength = character.starships[1].length;
const secondShipName = character.starships[1].name;
if (checkProperty && checkArray) {
if (secondShipLength >= 2) {
return secondShipName;
} else {
return "none";
}
} else {
return "none";
}
}
Data
window.lukeSkywalker = require('./person-1.json')
window.leiaOrgana = require('./person-5.json')
window.obiWanKenobi = require('./person-10.json')
},{"./person-1.json":2,"./person-10.json":3,"./person-5.json":4}],2:[function(require,module,exports){
module.exports={
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"homeworld": "Tatooine",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"Revenge of the Sith",
"The Force Awakens"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Snowspeeder",
"model": "t-47 airspeeder",
"manufacturer": "Incom corporation",
"cost_in_credits": null,
"length": "4.5",
"max_atmosphering_speed": "650",
"crew": 2,
"passengers": 0,
"cargo_capacity": "10"
},
{
"name": "Imperial Speeder Bike",
"model": "74-Z speeder bike",
"manufacturer": "Aratech Repulsor Company",
"cost_in_credits": 8000,
"length": "3",
"max_atmosphering_speed": "360",
"crew": 1,
"passengers": 1,
"cargo_capacity": "4"
}
],
"starships": [
{
"name": "X-wing",
"model": "T-65 X-wing",
"manufacturer": "Incom Corporation",
"cost_in_credits": 149999,
"length": "12.5",
"max_atmosphering_speed": "1050",
"crew": 1,
"passengers": 0,
"cargo_capacity": "110",
"consumables": "1 week",
"hyperdrive_rating": "1.0",
"MGLT": "100",
"starship_class": "Starfighter"
},
{
"name": "Imperial shuttle",
"model": "Lambda-class T-4a shuttle",
"manufacturer": "Sienar Fleet Systems",
"cost_in_credits": 240000,
"length": "20",
"max_atmosphering_speed": "850",
"crew": 6,
"passengers": 20,
"cargo_capacity": "80000",
"consumables": "2 months",
"hyperdrive_rating": "1.0",
"MGLT": "50",
"starship_class": "Armed government transport"
}
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
},{}],3:[function(require,module,exports){
module.exports={
"name": "Obi-Wan Kenobi",
"height": "182",
"mass": "77",
"hair_color": "auburn, white",
"skin_color": "fair",
"eye_color": "blue-gray",
"birth_year": "57BBY",
"gender": "male",
"homeworld": "Stewjon",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"The Phantom Menace",
"Attack of the Clones",
"Revenge of the Sith"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Tribubble bongo",
"model": "Tribubble bongo",
"manufacturer": "Otoh Gunga Bongameken Cooperative",
"cost_in_credits": null,
"length": "15",
"max_atmosphering_speed": "85",
"crew": 1,
"passengers": 2,
"cargo_capacity": "1600"
}
],
"starships": [
{
"name": "Jedi starfighter",
"model": "Delta-7 Aethersprite-class interceptor",
"manufacturer": "Kuat Systems Engineering",
"cost_in_credits": 180000,
"length": "8",
"max_atmosphering_speed": "1150",
"crew": 1,
"passengers": 0,
"cargo_capacity": "60",
"consumables": "7 days"
},
{
"name": "Trade Federation cruiser",
"model": "Providence-class carrier/destroyer",
"manufacturer": "Rendili StarDrive, Free Dac Volunteers Engineering corps.",
"cost_in_credits": 125000000,
"length": "1088",
"max_atmosphering_speed": "1050",
"crew": 600,
"passengers": 48247,
"cargo_capacity": "50000000",
"consumables": "4 years"
},
{
"name": "Naboo star skiff",
"model": "J-type star skiff",
"manufacturer": "Theed Palace Space Vessel Engineering Corps/Nubia Star Drives, Incorporated",
"cost_in_credits": null,
"length": "29.2",
"max_atmosphering_speed": "1050",
"crew": 3,
"passengers": 3,
"cargo_capacity": null,
"consumables": null
},
{
"name": "Jedi Interceptor",
"model": "Eta-2 Actis-class light interceptor",
"manufacturer": "Kuat Systems Engineering",
"cost_in_credits": 320000,
"length": "5.47",
"max_atmosphering_speed": "1500",
"crew": 1,
"passengers": 0,
"cargo_capacity": "60",
"consumables": "2 days"
},
{
"name": "Belbullab-22 starfighter",
"model": "Belbullab-22 starfighter",
"manufacturer": "Feethan Ottraw Scalable Assemblies",
"cost_in_credits": 168000,
"length": "6.71",
"max_atmosphering_speed": "1100",
"crew": 1,
"passengers": 0,
"cargo_capacity": "140",
"consumables": "7 days"
}
],
"created": "2014-12-10T16:16:29.192000Z",
"edited": "2014-12-20T21:17:50.325000Z",
"url": "https://swapi.co/api/people/10/"
}
},{}],4:[function(require,module,exports){
module.exports={
"name": "Leia Organa",
"height": "150",
"mass": "49",
"hair_color": "brown",
"skin_color": "light",
"eye_color": "brown",
"birth_year": "19BBY",
"gender": "female",
"homeworld": "Alderaan",
"films": [
"A New Hope",
"The Empire Strikes Back",
"Return of the Jedi",
"Revenge of the Sith",
"The Force Awakens"
],
"species": [
"Human"
],
"vehicles": [
{
"name": "Imperial Speeder Bike",
"model": "74-Z speeder bike",
"manufacturer": "Aratech Repulsor Company",
"cost_in_credits": 8000,
"length": "3",
"max_atmosphering_speed": "360",
"crew": 1,
"passengers": 1,
"cargo_capacity": "4"
}
],
"starships": [],
"created": "2014-12-10T15:20:09.791000Z",
"edited": "2014-12-20T21:17:50.315000Z",
"url": "https://swapi.co/api/people/5/"
}
},{}]},{},[1]);
How I would approach the problem (Pseudo Code):
//Create a variable called starship2nd
//Assign starship2nd the 2nd starship of each character.
//Check the length of the 2nd starship of each character. [[I'm stuck on this phase.]]
//Return 'none' after the checker function iterates through the Object's array. [[[Not sure how to do this part either..]]
Failed Solutions (Are they repairable? O_O)
solution 1 (failed)
const starship2nd = character.starships[1].name
const shipLength = starship2nd.length
function checkLength () {
if (shipLength === 0) {
return 'none'
}
return checkLength()
Thank you for your time. ^_^
Here is some pseudo code for you
if (character has property 'starships' and it is an array) {
if (length of starships is at least 2) {
return name property of second starship
} else {
return none
}
} else {
return none
}
You might think that some of those checks are overkill and not necessary since you know your input, but it is always good practice to double check properties and lengths before you begin accessing and assuming.
I hope that helps you with reasoning about the problem.

proficient JSON structure for comment section between Patient and Doctor?

I'm currently developing a medical app with authentication functionality between patients and doctors.
Now the current JSON structure for patients & doctor is as follows:
Patients
"Patients": {
"w14FKo72BieZwbxwUouTpN7UQm02": {
"name": "Naseebullah Ahmadi",
"profession": "Student",
"gender": "Male",
"type": "Patient",
"doctors": ["Ernest"],
"age": "20",
"DOB": "02/06/1997",
"address": "122 Atherstone Court",
"contactNumber": "07473693312",
"profilePicture": "../Images/profile.jpg",
"history": {
"age": "22",
"weight": "53",
"height": "172",
"bmi": "20.4",
"thermometer": "36.7",
"calories": "537",
"bpm": "87",
"fat": "11",
"allergies": ["Peanuts", "Penicilin"]
},
"appointments": [{
"date": "25th Jul",
"time": "13:00",
"type": "Doctor",
"name": "Ernest Kamavuako"
}],
"ecg": [""],
"heartSound": [""]
},
Where each Patient is identified by their Id "example: w14FKo72BieZwbxwUouTpN7UQm02"
Doctor
"Doctors": {
"VoxHFgUEIwRFWg7JTKNXSSoFoMV2": {
"name": "Ernest Kamavuako",
"gender": "Male",
"type": "Doctor",
"Patients": ["Naseebullah"],
"age": "30",
"dob": "20/12/1970",
"address": "122 Harrow Street",
"contactNumber": "07473033312",
"profilePicture": "../Images/profile.jpg"
}
}
Now the problem is: Each doctor is able to read comments that the patient has left to them, and likewise each patient is able to read comments that each doctor left.
Both principles are able to have a max limit of 50 comments.
Currently, I'm not sure how to represent the "comment" object and how it should be laid out.
This question is purely for the benefit of understanding the relation between actors that are being played.
You can have a json object for comments like this
"Comments": {
"<doctorsId>:<patientsId>": {
"doctorsComments" : '["comment1", "comment2"]',
"patientsComments": '["comment1", "comment2"]'
}
}
Here You can directly access the comment object if you have the doctors and patients ids.

how to get nested array data in jquery datatables

I have the following JSON data:
{
"00100": {
"claim_id": "21",
"reference_no": "00100",
"distributor_name": "Standard Match",
"group_name": "A",
"month": "Jun2017",
"grand_total": "268.532",
"details": [
{
"claim_id": "65",
"product_name": "Lucky Match Type 1",
"price": "102.00",
"quantity": "02",
"net_amount": "179.52"
},
{
"claim_id": "66",
"product_name": "Lucky Match Type 2",
"price": "101.15",
"quantity": "01",
"net_amount": "89.012"
}
]
}
}
I want to get this data in Jquery Datatables, but i want to out put like this showing in below image:
i guess you can't since jquery datatable will not work with table inside table.
Sorry if i am wrong.
please go through this for further reference
https://datatables.net/blog/2011-06-19
May be you can.

Nested For Loop Pass Variable

I need to get foreach value of "site[id]" take "purchase[id]". I use object keys because the data varies and i have no knowledge of the ids. What is the correct and most efficient way to achieve this?
var data = {
"user_id": null,
"created_at": "2016-11-09T05:52:42.279Z",
"total_prices": {
"final_price": "$173.11",
"shipping_price": "$13.18"
},
"notes": null,
"used_profiles": null,
"sites": {
"56c6cce830bb1f28f8000022": {
"info": {
"url": "a1supplements.com",
"name": "A1 Supplements",
"logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/56c6/cce8/30bb/1f28/f800/0022/small/56c6cce830bb1f28f8000022.png%3F1478498606243"
},
"prices": {
"shipping_price": "$6.95",
"final_price": "$86.90"
},
"details": {
"shipping_estimate": "2-5 Days"
},
"order_id": "fake_confirm_order_id",
"products": {
"458aa2317f92043a0713b37e03b47b2d": {
"original_url": "https://www.a1supplements.com/labrada-iso-leanpro",
"clean_url": "https://www.a1supplements.com/labrada-iso-leanpro",
"category_attributes": null,
"categories": [
"Everything Else"
],
"status": "done",
"required_fields": {
"quantity": {
"data": [{
"input_type": "text",
"input_name": "INPUT"
}]
},
"flavor": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
},
"size": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
}
},
"discounted_price": null,
"pickup_support": false,
"url": "https://www.a1supplements.com/labrada-iso-leanpro",
"required_field_values": {
"size": [{
"weight": "2267.985122017599",
"value": "5 Lbs.",
"text": "5 Lbs.",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": "",
"dep": {
"flavor": [{
"weight": "2267.985122017599",
"value": "Chocolate",
"text": "Chocolate",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": ""
}, {
"weight": "2267.985122017599",
"value": "Vanilla",
"text": "Vanilla",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": ""
}]
}
}]
},
"required_field_names": [
"size",
"flavor",
"quantity"
],
"weight": "2267.985122017599",
"site_categories": [
"Home",
"Protein",
"Whey Protein Powder",
"Whey Protein Isolate"
],
"description": "100% Premium Whey Protein Isolate!\n<strong>Made with 100% PURE WHEY PROTEIN ISOLATE</strong> as the sole protein source, ISO LeanPro contains ZERO carbs, sugar, lactose and gluten—no junk, fillers, or cheap blends.<br><br><strong>ISO LeanPro is not a blend</strong> containing whey protein concentrate, peptides, or other proteins. You get only 100% pure whey protein isolate as the source of protein.<br><br><strong>ISO LeanPro is sugar-free,</strong> and carb-free, so it&apos;s perfect for dieting.<br><br><strong>ISO LeanPro is lactose-free,</strong> so there is no bloating, gas, or indigestion associated with cheap proteins.<br><br><strong>ISO LeanPro is gluten-free,</strong> perfect for individuals who must avoid gluten because they suffer from gluten sensitivities.<br><br><strong>ISO LeanPro is perfect for athletes,</strong> bodybuilders, and fitness enthusiasts who demand the purest, highest quality protein available on the market.<br><br><strong>ISO LeanPro has a BV of 159,</strong> making it more bio-available than any other protein source. The most accurate way of testing the bioavailability of proteins is with the BV (Biological Value) method which measures actual nitrogen retention in humans.<br><br><strong>ISO LeanPro 100% Whey Protein Isolate</strong> is an excellent source of all the essential amino acids and is extremely rich in the branched chain amino acids (BCAAs), leucine, isoleucine, and valine.<br><br><strong>Branched chain amino acids</strong> make up one-third of muscle protein and are important to athletes because training increases the body&apos;s demand for them. An adequate supply of BCAAs in the blood is insurance against loss of muscle size and strength. ISO LeanPro is also high in glutamine, which accounts for approximately 60% of all free amino acids in the body.<br><br><strong>Labrada Nutrition CEO and IFBB Pro Bodybuilding</strong> Hall of Famer Lee Labrada says, "ISO LeanPro is a very pure protein powder designed for elite athletes and bodybuilders who want the very best money can buy. ISO LeanPro is very quickly absorbed and utilized, so it&apos;s perfect for use right before and after training, to put the body into an anabolic state."<br><br> <strong>FDA</strong>: These statements have not been evaluated by the Food and Drug Administration. This product is not intended to diagnose, treat, cure, or prevent any disease.<br><br><i>Shop our 100% secure server and get your supplements at the lowest prices everyday! NOBODY beats our overall price.</i><br> <div> <h3>Supplement Facts</h3> <strong>Supplement Facts:</strong><br><br>Serving Size: 1 Scoop (32g)<br>Servings Per Container: 71<br><br>Amount Per Serving <br>Calories 115 <br>Calories from Fat 9 <br>Total Fat 1 g 2%<br>Saturated Fat 0 g 0%<br>Trans Fat 0 g <br>Cholesterol 0 mg 0%<br>Sodium 150 mg 6%<br>Potassium 150 mg 5%<br>Total Carbohydrate 1 g 0%<br>Dietary Fiber 0 g 0%<br>Sugars 0 g <br>Protein 25 g 50%<br>Vitamin A 0%<br>Vitamin C 0%<br>Calcium 13%<br>Iron 0%<br><br>Ingredients: Cross-Flow Micro Ultrafiltered Whey Protein Isolate, Natural & Artificial Flavors, Dutched Cocoa, Cellulose Gum, Salt, Acesulfame Potassium, Sucralose.<br><br>NOTE: Supplement facts and ingredients may vary by flavor.<br><br>Allergen Information: Contains Milk, Soy.<br><br> </div> <div> <h3>Directions</h3> <p>Directions: Glass – Fill glass with 4–6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro, and mix with a spoon. Shaker – Fill shaker with 4–6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro. Cover and shake. Blender – Fill blender with 4–6 oz. of water or your favorite beverage. For a creamy ice cream flavor, add a handful of ice cubes. Add 1 scoop of ISO LeanPro. Cover and blend.<br><br>Note: Manufacturers continually change product specifications. While we try our best to keep product descriptions up to date, they do not necessarily reflect the latest information available from the manufacturer. We are not responsible for incorrect or outdated product descriptions and/or images. <br> <br></p> </div>",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"original_price": "$129.99",
"price": "$79.95",
"title": "Labrada ISO LeanPro",
"input_fields": {
"quantity": "1",
"flavor": "Vanilla",
"size": "5 Lbs."
}
}
},
"status": "done"
},
"5679041130bb1f37570026f5": {
"info": {
"url": "bodybuilding.com",
"name": "Bodybuilding",
"logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/5679/0411/30bb/1f37/5700/26f5/small/5679041130bb1f37570026f5.png%3F1478589601755"
},
"prices": {
"final_price": "$86.21",
"shipping_price": "$6.23"
},
"details": {},
"failed_to_add_to_cart": null,
"order_id": "fake_confirm_order_id",
"products": {
"b634b0cc8751b14b54031c5c94d47de4": {
"original_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"clean_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"weight": "1000",
"category_attributes": null,
"categories": [
"Everything Else"
],
"status": "done",
"required_fields": {
"option 1": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
}
},
"discounted_price": null,
"original_price": null,
"pickup_support": false,
"url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"required_field_values": {
"option 1": [{
"weight": "",
"value": "56 Capsules",
"text": "56 Capsules",
"price": "$24.99",
"image": "https://store.bbcomcdn.com/images/store/skuimage/sku_ZL008/image_skuZL008_largeImage_X_70_white.jpg",
"extra_info": "clearance, clearance"
}]
},
"required_field_names": [
"option 1"
],
"extra_info": "clearance clearance",
"site_categories": [
"Zantrex-3 Fat Burner"
],
"description": "Famous High-Energy Component!*\nHigh Energy Fat Burning Support!*",
"image": "https://store.bbcomcdn.com/images/store/prodimage/prod_35283/image_35283_original_X_450_white.jpg",
"price": "$24.99",
"title": "Zantrex-3 Fat Burner",
"input_fields": {
"quantity": "1",
"option 1": "56 Capsules"
}
},
"ba621a59cac993a24789d390efb741fc": {
"title": "Hydroxycut CLA Elite Next Gen",
"price": "$54.99",
"image": "https://store.bbcomcdn.com/images/store/prodimage/prod_prod3990044/image_prodprod3990044_largeImage_X_450_white.jpg",
"description": "Advanced, Scientifically-Tested Weight Loss Driver*\nSupplies 95% Cla Plus L-Carnitine And Garcinia Indica",
"site_categories": [
"Hydroxycut CLA Elite Next Gen"
],
"extra_info": "Buy 1 Get 1 Free Buy 1 Get 1 Free",
"required_field_names": [
"option 1"
],
"required_field_values": {
"option 1": [{
"extra_info": "Buy 1 Get 1 Free, Buy 1 Get 1 Free",
"image": "https://store.bbcomcdn.com/images/store/skuimage/sku_MT4240203/image_skuMT4240203_largeImage_X_70_white.jpg",
"price": "$54.99",
"text": "100 Raspberry Flavored Softgels",
"value": "100 Raspberry Flavored Softgels",
"weight": ""
}]
},
"url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"pickup_support": false,
"original_price": null,
"discounted_price": null,
"required_fields": {
"option 1": {
"data": [{
"input_name": "SELECT",
"input_type": "select-one"
}]
}
},
"status": "done",
"categories": [
"Everything Else"
],
"category_attributes": null,
"weight": "1000",
"clean_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"original_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"input_fields": {
"quantity": "1",
"option 1": "100 Raspberry Flavored Softgels"
}
}
},
"status": "done"
}
},
"message": "done",
"final_message": "Hi! We've confirmed 2 orders:\n\nA1 Supplements total $86.90 vs our initial estimate of $85.90 (shipping $6.95 vs estimated $5.95).\n* products: Labrada ISO LeanPro.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nBodybuilding total $86.21 vs our initial estimate of $91.41.\n* products: Zantrex-3 Fat Burner; Hydroxycut CLA Elite Next Gen.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nTotal $173.11."
};
var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];
var jj = (data.sites);
for (var key in jj) {
if (jj.hasOwnProperty(key)) {
console.log(key + ": " + jj[key]);
var ee = (data.sites[jj].products);
for (var key in ee) {
if (ee.hasOwnProperty(key)) {
console.log(key + ": " + ee[key]);
}
}
}
}
When executing the code above I receive the following error because the variable from the first loop isn't getting passed to the second loop.
VM1172:301 Uncaught TypeError: Cannot read property 'products' of undefined(…)
A few things:
var ee = (data.sites[jj].products); won't work because jj is an object, not the key
You've declared key twice, so the inner loop won't be able to read the outer one simply because they have the same name.
It's generally better to use Object.keys(...).forEach(...) in these sorts of loops as long as you don't need legacy browser support. The parameter of the forEach call will be a function that will be executed once per key in the object. More info here.

Query with join between documents

I would like to create a view in CouchDb which contains some fields from multiple linked documents.
My documents are something like this:
/*Products:*/
{
"_id": "Products:ABC",
"doctype": "Products",
"productCode": "ABC",
"description": "The best product you ever seen",
"category_id": "Categories:1",
"brand_id": "Brands:52"
},
{
"_id": "Products:DEF",
"doctype": "Products",
"productCode": "DEF",
"description": "DEFinitely a good product",
"category_id": "Categories:2",
"brand_id": "Brands:53"
},
/*Categories*/
{
"_id": "Categories:1",
"categoryID": "1",
"description": "Awesome products"
},
{
"_id": "Categories:2",
"categoryID": "2",
"description": "Wonderful supplies"
},
/*Brands*/
{
"_id": "Brands:52",
"brandID": "52",
"description": "Best Items"
},
{
"_id": "Brands:53",
"brandID": "53",
"description": "Great Gadgets"
},
I would like to have a result like this:
/*View results: */
{
"id": "Products:ABC",
"key": "Products:ABC",
"value": {
"productCode": "ABC",
"description": "The best product you ever seen",
"category": {
"categoryID": "1",
"description": "Awesome products"
},
"brand": {
"brandID": "52",
"description": "Best Items"
}
}
},
{
"id": "Products:DEF",
"key": "Products:DEF",
"value": {
"productCode": "DEF",
"description": "DEFinitely a good product",
"category": {
"categoryID": "2",
"description": "Wonderful supplies"
},
"brand": {
"brandID": "53",
"description": "Great Gadgets"
}
}
},
The goal is to have a result that is a join between the three documents. Is it possibile?
As you can imagine I come from the SQL world, so maybe I am designing the database terribly wrong, so any advice on how to change the documents structure is welcome!
Thanks in advance!
Francesco
There are two ways to do this:
Use the query() API and linked documents (search the page for "linked documents")
Use the relational-pouch plugin
The advantage of the relational-pouch plugin is that, under the hood, it is faster than linked documents because it doesn't rely on building up a map/reduce index. The advantage of linked documents is that it is the more traditional way of solving this problem in CouchDB, and it doesn't rely on an extra plugin. Choose whichever one you like. :)
Edit: re-reading your question, I see you want to join 3 different document types together. Currently that is not possible with linked documents (you can only "join" two types), whereas it is possible with relational-pouch. So I guess that makes the decision easy. :)

Categories

Resources