Angular2 filtering of array with one property and display the corresponding value - arrays

I have a dropdown with list of states which I am getting through services.In JSON I get list of states with id and label. For ex. id:NJ,label:New Jersey. I have a different response coming from backend which gives me id of 5 states-
ex:
"filters": [
{
"name": "listedStates",
"includedCodes": [
"AZ",
"NJ",
"IN",
"OH",
"WI"
]
}
to populate the list of entire US states in the dropdown, I am iterating like this-
this.addressService.getStates().subscribe(
(data) => {
console.log(data);
if (data) {
//filter with filters array
data.states.forEach(i => {
console.log(data.states);
this.newBaseStatesList.push({ 'value': i.id, 'text': i.label });
console.log(this.newBaseStatesList);
});
}
},
(error) => {
//console.log("An error occurred ");
}
);
Right now my dropdown is getting populated with all the state items in the array whereas I would want to display only 5 states in the dropdown mentioned in the filters array. The problem here is the response I am getting from backend has only ids not the labels and the dropdown should contain the labels values. So I have to somehow map these codes with the states array in such a way that these 5 states get filtered and populated.
My object is in format-
{
id:NJ,
label:New Jersey
}
I would like to check with the state codes in filters array with the states array and display the respective labels. Right now, the entire states are getting populated instead of the 5 states mentioned in the filters array.

You can achieve using as below
this.filters.forEach((filter)=>{
filter.includedCodes.forEach((code)=>{
this.newBaseStatesList.push(_.takeWhile(this.data.states, { 'id': code}))'
});
})
Note:I am using Lodash.
I am not sure the syntax that your service returns for the this.data.states so work need to on it based on the sample json

Related

Delete many items from array of documents in mongodb that match this value

I am trying to delete all documents from an array of documents that match this value but cannot figure it out,
This is my delete query that is not working, courses is the array I need to be in and code is the document I need to check to see its value for deletetion. So if courses.code == 123, then delete and keep going sort of thing.
result = await mongoClient.db(DB_NAME).collection("technologies").deleteMany({ 'courses': {$in: 'courses.code'} });
That is what it looks like in my collection.
"name": "Sass",
"description": "Sass (Syntactically awesome style sheets) is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS).",
"difficulty":2,
"courses":[
{"code":"PROG2700","name":"Client Side Programming"},
{"code":"PROG3017","name":"Full Stack Programming"}
]
},
Any help would be great, thanks!
You can filter documents that contain the field you want to update
Do tests before updates on the original collection.
After some searches, I've found this method:
const filter = { }
db.collection.update(filter,
{
$pull: {
"courses": {
code: {
$in: [
"PROG3017",
"PROG2700"
]
}
}
}
},
{
multi: true
})
This pulls out any element in the array where the value of code is $in the array.

How to iterate through a JSON array and display specific information based on an API response value in React?

I'm building a ReactJS web application, I have a JSON array:
[{
"2149166938": {
"name": "Classical-42",
"icon": "/common/destiny2_content/icons/e6885dab15cafeaf0dbf80f1ff9b5eb8.jpg"
},
"2149166939": {
"name": "Countess SA/2",
"icon": "/common/destiny2_content/icons/de8906743db9fce201b33802c8498943.jpg"
},
"2154059444": {
"name": "The Long Goodbye",
"icon": "/common/destiny2_content/icons/fe07633a2ee87f0c00d5b0c0f3838a7d.jpg"
}
}]
When I make a call to an API I am returned a value of lets say 2154059444 which is the same value as the last object in my JSON file.
How would I iterate through the JSON file to find the object which has a value of 2154059444 and then access and render it's child values like name or icon?
you can do something like this. Your array is not proper please edit.
Create filtered data :
//here i am addding single dummy point you can make your function
l
et filteredData = [].concat(data.map(test => {
if(Object.keys(test)[0]==="2154059444"){
return test["2154059444"]
}
})).filter(Boolean)
and simply render it app like this .
{ filteredData.map(test => <div>{test.name}</div>)}
Here is live link
This is simple. JSON is equivalent to Javascript object. So you can do something like result[0]["2154059444"]. You might want to use JSON.parse for converting the JSON string to Javascript object.

Convert an iterable map object to array object in ReactJS

I'm trying to load some json file in a DropdownList from react-widgets. When I load the json file the data type looks like this:
Map {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
__altered
:
false
__hash
:
undefined
__ownerID
:
undefined
_root
:
ArrayMapNode
size
:
1
__proto__
:
KeyedIterable
While the Dropdown component (from react-widgets) needs an array! So It makes this error:
Failed propType: Invalid prop `data` of type `object` supplied to `DropdownList`,
expected `array`. Check the render method of `Uncontrolled(DropdownList)`.
I can't load the json file directly and I have to use ajax to load it (or technically I can but it's a huge file and each time the user click on the dropdown list it takes couple of seconds to load the data from file). How can I convert this to an array?
P.S. The json file looks like this:
{
"items":[
{
"id": "aaa",
"name": "english"
},
{
"id": "aab",
"name": "Swedish"
},
]
}
I think you're looking for something along the lines of:
var dropdownList = jsonObject.items.map((item, i) => {
return (
<option key={i} val={item.id}>{item.name}</option>
);
})
The Array.prototype.map function simply goes over a list and produces a new list of the same size but with changes based on the modifier/callback function.
Update based on comment:
Based on the docs for DropdownList, you have two options for passing data to the list: a flat array of item names, or a list of objects with specific keys for the item name and value.
Option 1: flat list of item names
var itemNames = jsonObject.items.map((item) => item.name );
Option 2 : list of objects
var items = jsonObject.items.map((item) => {
return {
textField: item.name,
valueField: item.id
}
});
The benefit to using the second option would be when someone selects one of the items, the event that is created with point to the val attribute of the HTML <option>. This is useful for you especially since your ids and names are not the same. An example:
Option 1 (from above):
<DropwdownList
data={itemNames}
onSelect: (event) => {
// Will give the `val` attribute set by DropdownList
// This might be the item name, or it might be something unique to DrowdownList
console.log(event.target.value);
}
/>
Option 2 (from above):
<DropwdownList
data={items}
onSelect: (event) => {
// Will give the `valueField` attribute you set, which for you is the item's `id` field
// This might be the item name, or it might be something unique to DrowdownList
console.log(event.target.value);
}
/>

How to iterate by time (in seconds) through an array with AngularJS

I have this JSON object that contains an array of devices types and each type has an array of brands:
{
"types": [
{
"type": "phone",
"brands": [“samsung”,”apple”,”LG”, … //a list of brands]
},
{"type": "PC",
"brands": [“DELL”,”apple”,”HP”, … //a list of brands]
},
…// a list of types
]
}
Using AngularJS ng-repeat I can iterate through every array , but I want to show the list of brands one by one in the same button , every value is shown for 2 seconds , in infinite loop, but I can’t figure out a way to do that.
you dont need ng-repeat for this. given that you need to display only one element at a time.
vm.display = {
count : 0,
current : null,
repeat : function() { $interval( vm.display.changeElement(), 2*1000) }
changeElement : function() { vm.display.current = list[vm.display.count] ; vm.display.count++; }
}
then just call vm.repeat() after getting data from server
As mentioned earlier, you can use $interval instead of ng-repeat to do this.
$interval(function(){
$scope.buttonLabel =$scope.data.types[0].brands[$scope.count%3];
$scope.count++;
},2000);
I hope this is what you need. :)
http://plnkr.co/edit/8VIJAN?p=preview

$q.all(promises)and structure of promises object to collect the returned data

I am using Angularjs $q.all(promises) to make multiple REST call and then collecting the data once promise is successful. I have following following.
If "promises is simple array then it works Plunker
var promises = [
Users.query().$promise,
Repositories.query().$promise
];
If "promises" is simple object then also it works Plunker
var promises = {
users: Users.query().$promise,
repos: Repositories.query().$promise
};
If "promises" is nested object then it is not working. For my requirement I need nested object to remember the input parameters. Plunker
var promises = {
users: {"phx":Users.query().$promise},
repos: {"phx":Repositories.query().$promise}
};
These plunkr are just to simulate my problem. However I want this approach in real project for following requirement.
I have list of 12 product
Each product has "details", "benefits" and "offers" data
I have separate REST API services for "details", "benefits" and "offers" having :productID as parameter
I am making call in following order
a. Loop for each cards
b. For each card, make a REST API call for "details", "benefits" and "offers"
c. Add #b steps into "promises" object
d. call
$q.all(promises).then(function(results) {
// Here need logic to compile the result back to product
// and corresponding "details", "benefits" and "offers" mapping
}
and get the data back
Following is json structure I needed to collect my response.
{
"prod1": {
"benefits": {},
"offers": {},
"pages": {
"productPage": {}
}
}
},
"common": {
"benefits": {},
"pages": {
"commonBenefit": {}
},
"others": {}
}
How can I achieve this?
If you really need it, you can wrap the nest with $q.all like this:
var promises = {
users: $q.all({"phx": Users.query().$promise}),
repos: $q.all({"phx": Repositories.query().$promise})
};
plnkr.co

Resources