IGDB API, ionic, angular - angularjs

Have anybody an idea, how I can split these in Typescript or JS:
{ "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", "ALL": "Albanian Lek" }
I want only the names like this:
AED
AFN
ALL

you are doing it wrong, first of all modify your object to array of objects like below
let currencies = [
{
code: "AED",
fullName: "United Arab Emirates Dirham"
},
{
code: "AFN",
fullName: "Afghan Afghani"
},
{
code: "ALL",
fullName: "Albanian Lek"
}
];
now you can traverse through it like
currencies.forEach(val => {
//use val.code to get desired currencies codes
})

You can use Object.keys (link) to extract all keys from some object.
var countries = { "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", "ALL": "Albanian Lek" }
var codes = Object.keys( countries );
console.log( codes ); // [ "AED", "AFN", "ALL" ]

Related

Using multiple forEach chained into each other and iterating over a single array, Need an equivalent method to handle the same without forEach looping

My array contains multiple arrays and to access the objects, I have used multiple forEach. How do I handle using multiple foreach loops?
Kindly suggest an equivalent method to avoid this chaining.
See the below snippet and suggest a better solution to optimize my code.
var v = [
{
"company_name": "Apple",
"company_code": "AP",
"states": [
{
"state_name": "California",
"state_code": "CA",
"locations": [
{
"location_name": "USA - New York",
"location_code": "US - NY"
},
{
"location_name": "USA - San Francisco",
"location_code": "US - SF"
}
]
},
{
"state_name": "Rajasthan",
"state_code": "RJ",
"locations": [
{
"location_name": "Udaipur",
"location_code": "UDR"
},
{
"location_name": "Jaipur",
"location_code": "JP"
}
]
}
]
}
]
var AllData=[]
for (let i = 0; i < v.length; i++) {
const data = v[i];
//console.log(data);
data.states.forEach((state) => {
state.locations.forEach((location) => {
const ELEMENT_DATA = {
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name,
};
AllData.push(ELEMENT_DATA);
});
});
}
console.log(AllData);
Not really an optimisation, more of a readability improvement:
const arr = v.map(data =>
data.states.map(state =>
state.locations.map(location =>
({
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name
})
)
)
);
Check the following snippet to see if the output is the same.
var v = [{
"company_name": "Apple",
"company_code": "AP",
"states": [{
"state_name": "California",
"state_code": "CA",
"locations": [{
"location_name": "USA - New York",
"location_code": "US - NY"
},
{
"location_name": "USA - San Francisco",
"location_code": "US - SF"
}
]
},
{
"state_name": "Rajasthan",
"state_code": "RJ",
"locations": [{
"location_name": "Udaipur",
"location_code": "UDR"
},
{
"location_name": "Jaipur",
"location_code": "JP"
}
]
}
]
}]
const arr = v.map(data =>
data.states.map(state =>
state.locations.map(location =>
({
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name
})
)
)
);
console.log(arr)
This is basically your code, looping on each of the properties, it is just more easy to read.

How do i filter the array in object of array?

How do i filter roles in this array to return true when "Admin" is found?
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}]
Use .filter() and .includes():
const admins = array.filter((u) => u.roles.includes("Admin"))
1.Did u mean to return a boolean overall?
In Js es6, you could use .some() MDN web docs
it's nice and simple :)
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}, {
"country": "test",
"roles": [
"Normal"
]
}]
const result = array.some(o => Boolean(o.roles.some(role => role === 'Admin')))
console.log(result) // return true
2.Or, did u mean that it returns a new array in which each roles become a boolean depending on having 'Admin' or not?
If it is, .some() works as well :)
Try below:
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}, {
"country": "test",
"roles": [
"Normal"
]
}]
const result = array.reduce((acc, curr, index) => {
const item = Object.assign({}, curr, { roles: curr.roles.some(o => o === 'Admin') })
acc.push(item)
return acc
}, [])
console.log(result) // return true
or if it filter an array, my answer is the same as Tobias' :)
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}]
const val = array.map((a) => a.roles.includes('Admin'))
console.log(val) //return true

How to search and filter in array of objects on setState

I'm trying to create a search based on an array of objects with react which data is in this format:
const data = [
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
},
{
"name": "Ananas",
"desc": "juice, ananas, water"
}
]
},
{"category 2" : [
{
"name": "Banana Split",
"desc": "Banana, ice cream, chocolat, topping",
"allergens": "nuts"
},
{
"name": "Mango Sticky Rice",
"desc": "Mango, rice, milk",
"allergens": ""
}
]
}
]
I stored this data inside useState declaration to be able to render accordingly on data chnage:
const [filteredBySearch, setFilteredBySearch] = useState(data)
I have an input where we can type anything and set inside useState declaration.
Goal:
If I type in my input:
"Jui"
Output should be:
console.log(filteredBySearch)
/* output:
[
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
},
{
"name": "Ananas",
"desc": "juice, ananas, water"
}
]
},
{"category 2" : []
}
]*/
Exemple 2:
If I type in my input:
"Orange banana"
Output should be:
console.log(filteredBySearch)
/* output: [
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
}
]
},
{"category 2" : [
{
"name": "Banana Split",
"desc": "Banana, ice cream, chocolat, topping",
"allergens": "nuts"
}
]
}
]*/
I've try creating a new object with map and filter and set it with setFilteredBySearch, but I can't get anything, even creating this new object.
This the full component:
import Card from '../components/Card'
import React, { useState } from 'react';
export default function IndexPage({ data, search }) {
//search is the result of input value set on a useState
//Filter categoriesFoods by search
const [FilteredBySearch, setFilteredBySearch] = useState(data)
return (
<div className="main-content">
<div className="card-container">
{
FilteredBySearch.map(function(el, i) {
return (
<div key={i}>
<h2 className="category" id={Object.keys(el)}>{Object.keys(el)}</h2>
{
el[Object.keys(el)].map (function(itm,index){
return <Card key={index} infoItem={itm}/>
})
}
</div>
)
})
}
</div>
<style jsx>{`...`}</style>
</div>
)}
Any idea for me ?
Thanks a lot for your guidance!
I think this is what you are looking for. I have created below utilities for filtering as per your requirement.
const dataObj = [
{
'category 1': [
{
name: 'Orange',
desc: 'juice, orange, Water',
},
{
name: 'Ananas',
desc: 'juice, ananas, water',
},
],
},
{
'category 2': [
{
name: 'Banana Split',
desc: 'Banana, ice cream, chocolat, topping',
allergens: 'nuts',
},
{
name: 'Mango Sticky Rice',
desc: 'Mango, rice, milk',
allergens: '',
},
],
},
]
const checkIfInputMatches = (input, desc) => input.toLowerCase().split(" ").some(o => desc.toLowerCase().includes(o))
const filterByInput = (data, input) => {
let finalResult = [];
data.forEach(d => {
let keys = Object.keys(d);
let values = Object.values(d);
finalResult = [...finalResult, ...values.map((obj, index) => {
let result = obj.filter(o => checkIfInputMatches(input, o.desc))
return {[keys[index]]: result}
})]
})
return finalResult
}
console.log(filterByInput(dataObj, 'JUI'))
console.log(filterByInput(dataObj, "orange"))
console.log(filterByInput(dataObj, "rice"))
console.log(filterByInput(dataObj, "Orange banana"))
Hope this helps.

Iterating through JSON data using the map function

Here is the app working with the one dimensional data set:
https://boiling-coast-12353.herokuapp.com/
I wrote code that made clickable buttons for each country in my data. But now I need to use a data set structured differently so I can transform the data.
My data set is now like this:
{
"2010": [
{ "Country": "Argentina", "Percentage": 10.44 },
{ "Country": "Bolivia", "Percentage": 51.62 },
...
],
"2011": [
{ "Country": "Argentina", "Percentage": 10.34 },
{ "Country": "Bolivia", "Percentage": 51.62 },
...
],
....
}
Im trying to generate a button for each country, but the code I used before no longer works:
{
this.state.data.map((data, index) => (
<button key={index}className="button-primary" onClick={() => {this.onChooseCountry(index);
}}><span className="btn-content" tabindex="-1">
</span>{data.Country}</button>
))
}
What you have actually done is changes your data from an array to JSON Object. Here is the following code on how to iterate through a nested JSON array of your structure:
class App extends React.Component{
render(){
var json = {
"2010":[{ "Country": "Argentina", "Percentage": 10.44 },
{ "Country": "Bolivia", "Percentage": 51.62 }],
"2011":[{ "Country": "Argentina", "Percentage": 10.44 },
{ "Country": "Bolivia", "Percentage": 51.62 }]
};
return <div> {Object.keys(json).map(year => json[year].map(data => <button> {year} | {data["Country"]}</button>))} </div>
}
}
ReactDOM.render(
<App/>,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>

Angular select ngChange get the parent json object key not the value

I've created a hypothetical example; since i can't share my real example with you all. So forgive my hasty json file i created.
To the problem. Say i have a select populated like so using a json file which contains an array of (US State) objects:
State.json
{ "states":
[
{
code: "AL",
name: "Alabama"
},
{
code: "AK",
name: "Alaska"
},
{
code: "AS",
name: "American Samoa"
},
{
code: "AZ",
name: "Arizona"
},
{
code: "AR",
name: "Arkansas"
},
{
code: "CA",
name: "California"
},
{
code: "CO",
name: "Colorado"
},
{
code: "CT",
name: "Connecticut"
},
... etc...
]}
I pull in the json file and set it to a scope item like so:
main-controller.js
app.controller('MainCtrl', function ('$scope') {
$scope.states = [
{ code: "AL": name: "Alabama" },
//etc
];
$scope.selectStateChange = function (stateCode) {
console.log(stateCode);
}
});
index.html
Here's my select:
<select ng-model="selectedState" ng-change="selectStateChange(selectedState)">
<option ng-repeat="state in states">{{state.name}}</option>
</select>
My Problem
How does one get the actual state code to be passed into function selectStateChange on my ng-change?
You should try using ng-options instead of a ng-repeat on options.
This way your model will be up to date and it will be quite convenient to access the selected object.
It should looks like this in your case :
<select ng-model="selectedState" ng-options="state.name for state in states" ng-change="selectStateChange()">
</select>
and your JS should display your object:
app.controller('MainCtrl', function ('$scope') {
$scope.states = { "AL": "Alabama", //etc }
$scope.selectedState = null;
$scope.selectStateChange = function () {
console.log(selectedState);
}
});
This way, selectedState is equal to {
code: "AL",
name: "Alabama"
}
What get's logged into the console by console.log(stateCode);?
Did you try
$scope.selectStateChange = function (selectedState) {
console.log(selectedState.code);
}

Resources