JavaScript looping through multimensional JSON arrays - javascript

I've been unable to locate the correct solution to my problem here. I'd like to loop through the nested Products arrays to display each Product name. Is it possible with what I've written, or do I need to re-write it in a way that allows me to query what I need easier?
[
{
"category":"A",
"products":[
{
"id":1,
"name":"Product 1",
"description":"Description of my product 1."
},
{
"id":2,
"name":"Product 2",
"description":"Description of my product 2."
},
{
"id":3,
"name":"Product 3",
"description":"Description of my product 3."
}
]
},
{
"category":"B",
"products":[
{
"id":4,
"name":"Product 4",
"description":"Description of my product 4 in cat B."
},
{
"id":5,
"name":"Product 5",
"description":"Description of my product 5 in cat B."
},
{
"id":6,
"name":"Product 6",
"description":"Description of my product 6 in cat B."
}
]
}
]

Assuming that this whole structure is in a variable called data:
data.forEach(function(category) {
if (category.hasOwnProperty('product')) {
category.products.forEach(function(product) {
console.log(product.name);
});
}
});
The outer forEach loops through all of the category objects. The inner forEach loops goes through all of the products objects in each category.

In general looping through an array things = [...] is done like this:
for( var i=0; i<thing.length; i++ ) {
// do stuff with thing[i]
}
Looping through an object things = {...} is done like this:
for( key in things ) {
if( things.hasOwnProperty(key) ) {
// do stuff with things[key] or key.
}
}
You can nest them all you like.
In your case, if we name your original data structure items, then
(see http://jsfiddle.net/7yc5arLe/):
for( item=0; item<items.length; item++ ) {
console.log('category is '+items[item].category);
for( product=0; product<items[item].products.length; product++ ) {
p = items[item].products[product];
for( key in p ) {
console.log(' product '+key+' is '+items[item].products[product][key]);
}
}
}
will output
category is A
product id is 1
product name is Product 1
product description is Description of my product 1.
product id is 2
product name is Product 2
product description is Description of my product 2.
product id is 3
product name is Product 3
product description is Description of my product 3.
category is B
product id is 4
product name is Product 4
product description is Description of my product 4 in cat B.
product id is 5
product name is Product 5
product description is Description of my product 5 in cat B.
product id is 6
product name is Product 6
product description is Description of my product 6 in cat B.

Of course it is possible.
To loop over an array [] :
for (initialization; condition; update) {
...
}
To loop over an object {} :
for (variable in object) {
if (object.hasOwnProperty(variable)) {
...
}
}

Related

delete an item in an object array by id [duplicate]

This question already has answers here:
Find and remove objects in an array based on a key value in JavaScript
(14 answers)
Closed 1 year ago.
I want to delete an item based on its id.
I retrieve id from the cell where I click but I don't know how to retrieve id in the array to be able to compare it to that of the click to delete only the one selected and not all of the array, I'm not sure which method to use
My item.json
[{
"id": "e3c387fd-7cf1-4d5b-9825-cef745c0ab99",
"name": "item 1",
"fans": {},
"cell": [{
"id": "e2021621-9c74-4960-bf47-f6ad917ee40b",
"name": "cell 1 item 1",
},
{
"id": "d5129940-716c-47a3-81b5-f2c90e69b602",
"name": "cell 2 item 1",
}
]
},
{
"id": "79fe939b-4c64-4b73-bebd-6563f445920c",
"name": "item 2",
"fans": {},
"cell": [{
"id": "7b6b57c6-7b72-4a14-8932-51fc2e5f9b75",
"name": "cell 1 item 2",
},
{
"id": "b579f94f-605e-4c7a-a8c5-3aad9bfec9e2",
"name": "cell 2 item 2",
}
]
}
]
My function
trashItem(id) {
this.cellsListsData = this.cellsListsData.filter(cell => {
cell.id === id, console.log(cell.id, id);
});
}
this.cellsListsData = this.cellsListsData.filter(function(element) {
return element.id !== id;
});
or Just Get the index of it and then this.cellsListsData.splice(index, 1);
This would require traversing through the whole array and finding the index of object with the given id. Once you find the id, you can simply splice the array from that index with offset 1.
Below is a quick snippet for doing that.
var index_to_delete;
data.forEach(function(value, index) {
if (value.id == id_of_clicked_element) {
index_to_delete = index;
};
});
data.splice(index_to_delete, 1);
Note: Using filter will create a new array. So, if you are referencing the data array in some other variables, they will not get the new array. So, I recommend using the filter solution with caution. Also, some answers say to delete element at that index. This would remove that index from array and your array will be rendered inconsistent.

Firebase ordering and retrieving the index for a specific record

I'm using Firebase 2.4.2. I have a database as follows:
"items": {
"item1": {
"details": {
"name": "item 1",
"rate": 5
},
"item2": {
"details": {
"name": "item 2",
"rate": "4"
}
}
"item3": {
"details": {
"name": "item 3",
"rate": "6"
}
}
}
I have thousands of items and don't want to load them all in a table. Rather, I'd like to load the top10 along with the item that user has clicked on. So, if you are in the page: /items/details/item2, I'd like you see the top10 items in the database (based on their rates) and the item2 in a table. I'd also like to show the index of item2 in the ordered list.
ind id rate
1 item56 100
2 item33 98
...
143 item2 13
What we do normally -if the bandwidth is not issue- is to retrieve all data as follows (e.g. using AngularFire)
var ref = fbutil.ref('items').orderByChild('details/rate');
return $firebaseArray(ref);
However, I'd like to order them, retrieve the top10, and then retrieve the item2 (in this case) and its index (143) based on its rate.
How would I do that?
// For getting top 10
var ref = fbutil.ref('items').orderByChild('details/rate').limitToFirst(10);
return $firebaseArray(ref);
// For getting single
var ref = fbutil.ref('items').orderByChild('details/rate').equalTo(13);
var singleItem = $firebaseObject(ref);
Checkout the following link to see what methods firebase.database.Reference class supports.
https://firebase.google.com/docs/reference/js/firebase.database.Reference

Insert object into MongoDB object's array

I'm trying to add an object into an empty array that is stored in one of my collections.
Currently this is how I have my collection setup:
[
{
"name": "user_added",
"DRGs": []
},
...
]
How can I insert an object into the collection so that it looks like this;
[
{
"name": "user_added",
"DRGs": [
{
"code": "491",
"name": "Back & neck procedures"
}
]
},
...
]
Check out $push documentation.
You should be able to accomplish your goal with the following:
var collectionName = 'users'; // or whatever your actual collection name is
var objectToPush = {
code: "491",
name: "Back & neck procedures"
};
db.collection(collectionName).updateOne(
{"name": "user_added"},
{ $push: { "DRGS": objectToPush }}
);

"keys is not defined" in AngularJS's custom filter function [duplicate]

This question already has answers here:
Pro AngularJS - Could you help explain part of this code?
(2 answers)
Closed 6 years ago.
I was going through examples in one of Angular JS books that I have and ran into something I do not clearly understand. It has to do with custom filter and ng-repeat. Here are the codes
<a ng-click="selectCategory()" class="btn btn-block btn-default btn-lg">
Home
</a>
<a ng-repeat="item in data.products | orderBy: 'category' | unique: 'category'" ng-click="selectCategory(item)" class="btn btn-block btn-default btn-lg">
{{item}}
</a>
The following code is the controller attached to html body tag.
angular.module("sportsStore").controller("sportsStoreCtrl", function ($scope) {
$scope.data = {
products: [
{
name: "Product #1",
description: "A product",
category: "Category #1",
price: 100
},
{
name: "Product #2",
description: "A product",
category: "Category #1",
price: 100
},
{
name: "Product #3",
description: "A product",
category: "Category #2",
price: 210
},
{
name: "Product #4",
description: "A product",
category: "Category #3",
price: 202
}
]
};
});
The code for the custom filter is
angular.module("customFilters", []).filter("unique", function () {
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
What the custom filter is supposed to do is basically create a list of categories in $scope.data.products.
The code is working fine. What I do not understand is the role played by "var keys = {};" in the custom filter functions.
What is the intention for having variable "keys" and setting its properties' value to true?
The filter is executing on the data provided by $scope.data and the property "category". It checks for unique categories, only showing the first instance of a category.
As the loop executes, it is reading the value for the "category" key on each index of data.
The keys object acts as a tracker to track what values have been added to the results array.
By setting a value on the keys object, it makes it so if that value is encountered again, it will not satisfy the if condition and not add it to the results array.
In other words it executes on Product #1, reads the category as Category #1, adds it to the results array and creates a key["Category #1"] value of true.
Next, Product #2, it extracts the category value of "Category #1". Category #1 is already on the key object, so it will not add Product #2 to the result.
Next, Product #3, it extracts the category value of "Category #2", sees that it is not in the keys object, so it adds the "Category #2" to the results.
The resulting display should be the Product #1, #3, and #4 info if I am not mistaken.
By removing the keys[val] = true, it will cause all of the products to appear.

Array with levels - each level has values

I'm trying to create an array that has multiple levels and multiple values on each level. It needs to look something like this:
Value 1 level 1
Value 1 level 2
Value 1 level 3
Value 2 level 2
Value 2 level 1
How can I put something like this in an array?
You can make each level as a new array.
var myArray = new Array("Value 1 level 1", "Value 2 level 1");
myArray['Value 1 level 1'] = new Array("Value 1 level 2", "Value 2 level 2");
myArray['Value 2 level 2'] = new Array("Value 1 level 3");
you can have an array of objects like the below structure
var value=
{
value1level1:
{
value1level2:
{
value1level3:'somevalue'
}
}
};
var parentObj=[value];
Create a JSON structure like this:
[
{
"node":{
"Value 1":"level 1"
},
"children":[
{
"node":{
"Value1":"level 2"
},
"children":[
{
"node":{
"Value1":"level 3"
},
"children":[
]
}
]
}
]
},
{
"node":{
"Value 2":"level 1"
},
"children":[
]
}
]

Categories

Resources