Object Assign Nested Property Javascript - javascript

I am new to React JS (Javascript) and getting problems during merge the previous records with the new records in Pagination.
Below is the code:-
First Page Result
{
"status": 200,
"error": null,
"message": null,
"result": {
"data": [{
"SuraID": 116,
"ChapterID": 2,
"SuraName": "The Cow",
"Sajda": 0,
"Ayah": 286,
"Latin": "Al-Baqara",
"AyahText": [{
"id": 6283,
"text": "O children of Israel, remember the favours I bestowed on you. So keep your pledge to Me, and I will mine to you, and be fearful of Me, ",
"found": "1"
},
{
"id": 6290,
"text": "Remember, O children of Israel, the favours I bestowed on you, and made you exalted among the nations of the world. ",
"found": "1"
}
]
}],
"totalFound": 598,
"prev_page_url": "1",
"next_page_url": 2,
"totalPages": 27,
"percentage": 0.38390180331131357
}
Second Page Result
{
"status": 200,
"error": null,
"message": null,
"result": {
"data": [{
"SuraID": 116,
"ChapterID": 2,
"SuraName": "The bufallow",
"Sajda": 0,
"Ayah": 286,
"Latin": "Al-Baqara",
"AyahText": [{
"id": 6283,
"text": "O children of Israel, remember the favours I bestowed on you. So keep your pledge to Me, and I will mine to you, and be fearful of Me, ",
"found": "1"
},
{
"id": 6290,
"text": "Remember, O children of Israel, the favours I bestowed on you, and made you exalted among the nations of the world. ",
"found": "1"
}
]
}
"totalFound": 598,
"prev_page_url": "2",
"next_page_url": 3,
"totalPages": 27,
"percentage": 0.38390180331131357
}
Final Result Should like the below JSON
{
"status": 200,
"error": null,
"message": null,
"result": {
"data": [{
"SuraID": 116,
"ChapterID": 2,
"SuraName": "The Cow",
"Sajda": 0,
"Ayah": 286,
"Latin": "Al-Baqara",
"AyahText": [{
"id": 6283,
"text": "O children of Israel, remember the favours I bestowed on you. So keep your pledge to Me, and I will mine to you, and be fearful of Me, ",
"found": "1"
},
{
"id": 6290,
"text": "Remember, O children of Israel, the favours I bestowed on you, and made you exalted among the nations of the world. ",
"found": "1"
}
]
}, {
"SuraID": 116,
"ChapterID": 2,
"SuraName": "The Cow",
"Sajda": 0,
"Ayah": 286,
"Latin": "Al-Baqara",
"AyahText": [{
"id": 6283,
"text": "O children of Israel, remember the favours I bestowed on you. So keep your pledge to Me, and I will mine to you, and be fearful of Me, ",
"found": "1"
},
{
"id": 6290,
"text": "Remember, O children of Israel, the favours I bestowed on you, and made you exalted among the nations of the world. ",
"found": "1"
}
]
}],
"totalFound": 598,
"prev_page_url": "1",
"next_page_url": 2,
"totalPages": 27,
"percentage": 0.38390180331131357
}

Pseudo code:
let firstPageData = //from 1 fetch and after JSON.parse(data);
let secondPageData = //from 2 fetch and after JSON.parse(data);
let mergedPage= [...firstPageData,...secondPageData ];
or
let mergedPage= firstPageData.concat(secondPageData);

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.

Change JSON format/layout

I have a universal variable on my website which includes line items with relevant details. These line items are reflective of what the user has in their cart. I am integrating with a third party who require the data passed through to them to be formatted slightly different. The below is the data layer currently on my website:
"lineItems": [
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo"
},
"quantity": 1
}
]
The below is what format the third party needs:
"lineItems": [
{
"sku": "s83y016b5",
"name": "Jeans",
"description": "A super great pair of jeans.",
"category": "Everyday Wear",
"other": {"fieldName": "This can be a string or any value you like"}
"unitPrice": 11.99,
"salePrice": 11.99,
"quantity": 2,
"totalPrice": 23.98
"imageUrl": "http://www.my-website.com/a/p/shirt.jpeg",
"productUrl": "http://www.my-website.com/index.php/shirt.html",
}]
Obviously this needs to be dynamic based on the products in the cart. What I intend to do is use javascript to amend the data and send this to the third party via Google Tag Manager.
Any help would be greatly appreciated. Any questions welcome.
This should be close to what you're looking for.
let oldLineItems = "your object";
let newLineItems = {};
newLineItems.lineItems = [];
for (let i in oldLineItems.lineItems) {
newLineItems.lineItems[i] = {};
for (let key in oldLineItems.lineItems[i].product)
{
newLineItems.lineItems[i][key] = oldLineItems.lineItems[i].product[key];
}
}
See code below.
I'm not sure how your lineItems object is set up, but below I just created an array called line Items. If line items is a key in an object which I suspect from your snippet above, you will have to go a level deeper in the for loops used in my example below.
Simply add further details to the new object in the nested for in loops below.
var lineItems =
[
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 1
},
{
"product": {
"id": "s83y01699",
"sku_code": "s83y01699",
"url": "/en-gb/pants/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/pants.jpeg",
"name": "Pants",
"manufacturer": "",
"category": "Casual Wear",
"stock": 90,
"currency": "au",
"unit_sale_price": 14,
"unit_price": 14,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 14
},
];
var newLineItems = [];
for(var char in lineItems){
// Adding some values to newLineItems.
newLineItems.push({
sku: lineItems[char].product.sku_code,
name: lineItems[char].product.name,
description: lineItems[char].product.description,
category: lineItems[char].product.category,
quantity: lineItems[char].quantity
});
}
console.log(JSON.stringify(newLineItems));

How to get json data from multiple object levels [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I need to create a table from selected data generated by some rental software in json format via an api. The json data supplied is a list of products, and is quite extensive with objects containing other objects and arrays.
The problem comes when I need to retrieve the data from an object within an object. I want to get Name, weight and Rental Price form the data below. The rental price is in the rental_rate object.
{
"products": [
{
"id": 1404,
"name": "Product 1",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 1,
"stock_method_name": "Bulk",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "0.5",
"barcode": "#st2078",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 1404,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "10.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 5,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:49:47.755Z",
"updated_at": "2017-02-06T00:49:47.755Z",
"custom_fields": {
"barcode_notes": "Actual Leg Length is: 3'",
"product_serial_number": ""
},
"product_group": {
"id": 5,
"name": "Staging",
"description": "",
"created_at": "2017-02-05T22:20:53.465Z",
"updated_at": "2017-02-05T22:20:53.465Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 1782,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "10.0",
"category_prices": []
}
],
"sale_rates": []
},
{
"id": 2395,
"name": "Product 2",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 2,x
"stock_method_name": "Serialised",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "45.0",
"barcode": "",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 2395,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "0.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 6,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:50:35.834Z",
"updated_at": "2017-02-06T00:50:35.834Z",
"custom_fields": {
"barcode_notes": "",
"product_serial_number": ""
},
"product_group": {
"id": 6,
"name": "Cases",
"description": "",
"created_at": "2017-02-05T22:20:53.509Z",
"updated_at": "2017-02-05T22:20:53.509Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 2773,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "0.0",
"category_prices": []
}
],
"sale_rates": []
}
],
"meta": {
"total_row_count": 1376,
"row_count": 2,
"page": 1,
"per_page": 2
}
}
and here is the JS I am using to get the data:
$(document).ready( function() {
$.getJSON( 'https://myapi.com/products', function(data) {
$.each(data.products, function() {
$("table#prod").append("<tr><td>" + this['name'] + "</td><td>" + this['rental_rate.price'] + "</td><td>" + this['weight'] + "kg</td></tr>");
}); }); });
This works fine for name and weight, but not rental price. I have done a thorough search of most places on the internet and not found an answer - my javascript knowledge is limited, which probably means I am going about this all wrong, or not describing it well enough...
Any help or improved methods would be much appreciated!
this.name gets you the name
this.rental_rate gets you the nested rental rate object.
this.rental_rate.price gets you the price.
You can similarly use square bracket notation, but people often only do this when dot syntax won't work (because of spaces in the key).
e.g.
this["name"]
this["rental_rate"]["price"]
this["Invalid Key when accessed via dot syntax but fine with square brackets"]

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.

Filtering nested JSON data based on id Angularjs

I checked this plunker:
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
It worked for me to some extent. But my issue is i have a nested json data. Where the above filter code is not working. Following is my json data where I am filtering based upon "category_id" key.
JSON ::
[{
"category_id": 5,
"category_name": "Home",
"image": "Home_544f75960ee0e",
"parent_id": 0,
"i": 1,
"categories": [
{
"category_id": 7,
"category_name": "Home Safe",
"image": "Home Safe_5411af45ac923",
"parent_id": 5,
"i": 2,
"categories": [
{
"category_id": 13,
"category_name": "Mechanical Safes ",
"image": "Mechanical Safes _540ab92ee1ff7",
"parent_id": 7,
"i": 3
},
{
"category_id": 14,
"category_name": "Electronic Safes ",
"image": "Electronic Safes _540ab93c6e305",
"parent_id": 7,
"i": 4
}
]
},
{
"category_id": 8,
"category_name": "Video Door Phones ",
"image": "Video Door Phones _540ab57a466ff",
"parent_id": 5,
"i": 3
},
{
"category_id": 9,
"category_name": "Alarm Systems ",
"image": "Alarm Systems _540ab58b903e9",
"parent_id": 5,
"i": 4
},
{
"category_id": 10,
"category_name": "Home CCTV Cameras ",
"image": "Home CCTV Cameras _540ab59c59f44",
"parent_id": 5,
"i": 5
},
{
"category_id": 11,
"category_name": "Car Safes ",
"image": "Car Safes _540ab5b0dcc57",
"parent_id": 5,
"i": 6
},
{
"category_id": 12,
"category_name": "Hotel Safes ",
"image": "Hotel Safes _540ab5bddae51",
"parent_id": 5,
"i": 7
}
]},{
"category_id": 6,
"category_name": "Institution",
"image": "Institution_541304aa0a52d",
"parent_id": 0,
"i": 2,
"categories": [
{
"category_id": 15,
"category_name": "Physical Security Products ",
"image": "Physical Security Products _54130515e2cb3",
"parent_id": 6,
"i": 3,
"categories": [
{
"category_id": 18,
"category_name": "Record Protecting Equipment ",
"image": "Record Protecting Equipment _541305cb5f47a",
"parent_id": 15,
"i": 4
},
{
"category_id": 19,
"category_name": "Burglary and Fire Resistant Safes",
"image": "Burglary and Fire Resistant Safes_541305db69acf",
"parent_id": 15,
"i": 5
},
{
"category_id": 20,
"category_name": "Vault Equipment ",
"image": "Vault Equipment _541305e8d905c",
"parent_id": 15,
"i": 6
},
{
"category_id": 21,
"category_name": "Vault Accessories",
"image": "Vault Accessories_541305f6ed3a4",
"parent_id": 15,
"i": 7
}
]
},
{
"category_id": 16,
"category_name": "Premises Security Solutions ",
"image": "Premises Security Solutions _54130525074c9",
"parent_id": 6,
"i": 4
},
{
"category_id": 17,
"category_name": "Marine Solutions ",
"image": "Marine Solutions _54130530a10da",
"parent_id": 6,
"i": 5
}
]}]
here i am able to filter "category_id" = 5 but not able to filter "category_id" = 7
#josep Following is my code :
var categoriesdata = $filter('filter')($rootScope.catjsondata, {category_id:$stateParams.categoryId})[0];
here $rootscope.catjsondata contains the nested json data. $stateparams.categoryId will provide me the category_id of the object clicked in the list. so every time the id will change. Its not hardcoded. the values are dynamic.
Following is my controller code:
.controller('SubCategoriesCtrl', function($scope, $filter, $stateParams, $ionicNavBarDelegate, subcategoriesfactory, globalurlfactory, $rootScope) {
$scope.baseUrl = globalurlfactory;
console.log("$rootScope.catjsondata :: ", $rootScope.catjsondata);
console.log("$stateParams.categoryId :: ", $stateParams.categoryId);
var categoriesdata = $filter('filter')($rootScope.catjsondata, {category_id:$stateParams.categoryId})[0];
console.log("categoriesdata ::::: ", categoriesdata);
//$rootScope.catjsondata = categoriesdata;
$scope.categoryTitle = categoriesdata.category_name;
$scope.categoriesIn = categoriesdata.cats_in;
$scope.categories = categoriesdata.categories;
$scope.has_product = categoriesdata.has_product;
if(categoriesdata.has_product == "yes")
{
$scope.categoryTitle = categoriesdata.category_name;
$scope.products = categoriesdata.product;
}
$scope.goBack = function(){
$scope.isBack = true;
$ionicNavBarDelegate.back();
}})
As other mentioned, since there is no built in support for this (as far as I know) and you don't know the tree's depth, you have to recursively (or iteratively, recursively is simpler) find it.
Here is an updated plunker:
http://plnkr.co/edit/sFaBnCnhXzx08pVX5qXe?p=preview
Also the key function is attached for others (it is just a simple recursion that looks for the element by expression):
.filter('recursiveExpression', function($filter) {
return function(input, exp) {
return recursivelyFilterExpression(input, exp);
}
function recursivelyFilterExpression(input, exp) {
var filterResult = $filter('filter')(input, exp);
// Any result?
if (filterResult.length > 0) {
return filterResult[0];
}
if (angular.isArray(input) || angular.isObject(input)) {
for (var key in input) {
if (angular.isArray(input[key]) || angular.isObject(input[key])) {
var internalResult = recursivelyFilterExpression(input[key], exp);
if (internalResult) {
return internalResult;
}
}
}
}
return null;
}
});
** Make sure the expression is not costly to evaluate, in which case this won't be very so sufficient.
I think you need to iterate over the categories because they are nested inside the others.
I changed the json from your plunkr to simulate your real json.
Take a look at this one.
Nothing else comes to my mind right now.
--
Edited
Okay, this is the working plunkr with your JSON: plunkr

Categories

Resources