Iterating json data from an Api - javascript

I have an api from which I want to display the data, I have 2 arrays I think each one has category how would I iterate and display these 2 categories, so category Arts and category Entertainment.I would really appreciate the help. Thanks in advance
import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
const url="https://json-api-smaiil.herokuapp.com/books"
const Home = () => {
const [loading, setLoading] = useState(true)
const [books, setBooks] = useState([])
const fetchData =async()=>{
setLoading(true)
const response = await fetch(url)
const books = await response.json()
console.log(books)
setBooks(books)
}
useEffect(()=>{
fetchData();
},[])
return (
<div>
<h1 className='categories'>Categories</h1>
{books[0].map((book)=>{
return <li key={book.id}>{book.category}</li>
})}
</div>
)
}
export default Home
[
"Arts":[{
"category": "Arts"
Language: "English"
Narrated by: "Faith G. Harper PhD LPC-S ACS ACN"
Regular price: "$17.47"
Release date: "03-20-18"
bookName: "Unf--k Your Brain"
by: "Faith G. Harper PhD LPC-S ACS ACN"
category: "Arts and Entertainment"
id: "1"
},
{
Language: "English"
Length: "1 hr and 33 mins"
Narreted by: "James Taylor"
Regular price: "$9.95"
Release date: "01-31-20"
Series: "Words + Music"
bookName: " Break Shot: My First 21 Years"
by: "James Taylor"
id: "2"
}],
"Entertainment":[{
"category" :"Entertainment"
"id": "9",
"image": "https://m.media-amazon.com/images/I/51tpSb0iy+L._SL500_.jpg",
"bookName": "The Hiding Place",
"by": "Corrie ten Boom, John Sherrill, Elizabeth Sherrill",
"Narreted by": "Wanda McCaddon",
"Length": "8 hrs and 14 mins",
"Release date": "10-03-11",
"Language": "English",
"rating": "6,641 ratings",
"Regular price": "$24.95",
},
{
Language: "English"
Length: "1 hr and 7 mins"
Narreted by: "Aidan Gillen"
Regular price: "$9.95"
Release date: "03-31-15"
bookName: "The Art of War"
by: "Sun Tzu"
id: "12"
rating: "19,765 ratings"
}]
]

I can't comment because I don't have enough reputation, but it looks like you're using map wrong.
Array.prototype.map's callback takes in currentValue, index, and array Array.prototype.map as arguments. You can get the id, and category from the currentValue by destructuring (notice the curly brackets):
//...
books[0].map(({id, category}) => {
//...

Related

I need to fetch that 2nd query "Total Job" column with the first query as per the account_id is the primary key. How can I combine this two queries?

I need to fetch that 2nd query "Total Job" column with the first query as per the account_id is the primary key. How can I combine this two queries?
This is my Typescript NodeJS and mysql Rest API. How can I get this result?
const getPremiumJob = async (req: Request) => {
const connection = await createConnection()
try {
console.log(1)
const [premiumJob]: any = await connection.query(`SELECT rafp.account_id,rafp.foa_property_id,fpl.name,
rafp.text_value,rafp.int_value,rafp.float_value, fp.datatype FROM
rel_account_foa_property rafp join foa_property_localization fpl on rafp.foa_property_id=fpl.foa_property_id join
account on account.account_id=rafp.account_id inner join foa_property fp on fp.foa_property_id=rafp.foa_property_id where
fpl.name IN ('job title','enterprise','job description','job description','adress','image','job type','company_youtube','cover image') order by rafp.account_id ;`)
// const [premiumJob]: any = await connection.query(`SELECT t.tender_id,fpl.foa_property_id,fpl.name,rtfp.text_value,rtfp.int_value,rtfp.float_value, fp.datatype FROM tender t
// inner join rel_tender_foa_property rtfp on t.tender_id= rtfp.tender_id inner join foa_property_localization fpl on fpl.foa_property_id=rtfp.foa_property_id
// inner join foa_property fp on fp.foa_property_id=rtfp.foa_property_id `)
const [premiumJobCount]: any = await connection.query(` SELECT rel_account_foa_property.account_id,rel_account_foa_property.foa_property_id,rel_account_foa_property.text_value as "company name",COUNT(text_value) as "Total Job" FROM rel_account_foa_property join foa_property_localization on rel_account_foa_property.foa_property_id=foa_property_localization.foa_property_id join account on account.account_id=rel_account_foa_property.account_id where
foa_property_localization.name="enterprise" group by rel_account_foa_property.account_id,rel_account_foa_property.foa_property_id;`)
console.log(premiumJob)
const values = premiumJob.reduce((prev: any, curr: any) => ({
...prev,
[curr.account_id]: {
account_id: curr.account_id,
...prev[curr.account_id],
[(curr.name).replaceAll(' ', "_")]: curr[`${curr.datatype}_value`],
}
}), {}
as Record < string, any > )
return Object.values(values)
} catch (error) {
await connection.end()
throw error
}
}
I am getting below this result when I excecated first query
{
"account_id": 2641,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3005/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3005/public/uploads/company-logos/undefined"
}
I Need also Total Job from the second query add with this above query account_ID
I expected output is given below
{
"account_id": 2639,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3003/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3003/public/uploads/company-logos/undefined",
"Total Job": 1
}, {
"account_id": 2641,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3005/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3005/public/uploads/company-logos/undefined",
"Total Job": 1
}

Alternatives to using multiple reduce() functions inside a map() when handling deeply nested array of objects?

I have an object result which has a property records which is an array of objects with a single sample below:
const result = {
records: [
{
keys: ["names", "value", "country", "questions"],
length: 4,
_fields: [
"123ilSE",
[
"Longitude:5.1193",
"Latitude:52.3246",
"Agreeableness:0.147083333333333",
"Openness:0.211041666666667",
"Neuroticism:0.168833333333333",
"Extraversion:0.150291666666666",
"Conscientiousness:0.187041666666666",
"Angry:0.0441711768507957",
"Fear:0.020498564466834",
"Joy:0.875858068466186",
"Sadness:0.0477884039282798",
"Love:0.00839435961097478",
],
["Netherlands", "Netherlands"],
[
["Right"],
["Student Loan", "None"],
["Not at all, i’d rather rent all assets."],
["Another benefit"],
["Every two weeks", "Yearly a few times"],
[
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
["Two to Three Times a Week"],
[
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
[
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
[
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
["Every two weeks", "Yearly a few times"],
["Two to Three Times a Week"],
["Every Year"],
["Banking & Financial Services", "Unemployed"],
["I don't have a car"],
["Netherlands", "Netherlands"],
["3 - 4 persons"],
["Maybe, it depends if nothing betters comes up"],
["Desktop"],
[],
["I don't drive or have a car"],
[
"E, I can be found on social media platforms and maintain my profile but do little else.",
],
["None", "Healthcare Insurance"],
["None", "Hockey", "Hiking"],
["Hiking"],
["Unemployed"],
["1999-09-20 00:00:00"],
["Female"],
["Bachelor's degree"],
["Less then 20.000 EUR"],
["Single"],
["Netherlands", "Netherlands"],
["1399"],
["Prolific Participant"],
["English", "Dutch", "German"],
["Operations", "Unemployed"],
["None"],
["None"],
["Health & Beauty", "Clothing & Shoes", "Books", "None"],
["Whatsapp", "Youtube", "Instagram", "None"],
[
"TV (Local/Cable News Broadcast)",
"TV (Late Night Comedy, Other)",
"Radio (AM/FM, Internet, Satellite)",
"Print (Newspapers & Periodicals)",
"None",
],
],
],
},
],
};
I am transforming it to the following shape with a function I have:
const sample = [
{
name: "123ilSE",
longitude: 5.1193,
latitude: 52.3246,
agreeableness: 0.147083333333333,
openness: 0.211041666666667,
neuroticism: 0.168833333333333,
extraversion: 0.150291666666666,
conscientiousness: 0.187041666666666,
angry: 0.0441711768507957,
fear: 0.020498564466834,
joy: 0.875858068466186,
sadness: 0.0477884039282798,
love: 0.00839435961097478,
country: "Netherlands",
question1: ["Right"],
question2: ["Student Loan", "None"],
question3: ["Not at all, i’d rather rent all assets."],
question4: ["Another benefit"],
question5: ["Every two weeks", "Yearly a few times"],
question6: [
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question7: ["Two to Three Times a Week"],
question8: [
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question9: [
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question10: [
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question11: ["Every two weeks", "Yearly a few times"],
question12: ["Two to Three Times a Week"],
question13: ["Every Year"],
question14: ["Banking & Financial Services", "Unemployed"],
question15: ["I don't have a car"],
question16: ["Netherlands", "Netherlands"],
question17: ["3 - 4 persons"],
question18: ["Maybe, it depends if nothing betters comes up"],
question19: ["Desktop"],
question20: [],
question21: ["I don't drive or have a car"],
question22: [
"E, I can be found on social media platforms and maintain my profile but do little else.",
],
question23: ["None", "Healthcare Insurance"],
question24: ["None", "Hockey", "Hiking"],
question25: ["Hiking"],
question26: ["Unemployed"],
question27: ["1999-09-20 00:00:00"],
question28: ["Female"],
question29: ["Bachelor's degree"],
question30: ["Less then 20.000 EUR"],
question31: ["Single"],
question32: ["Netherlands", "Netherlands"],
question33: ["1399"],
question34: ["Prolific Participant"],
question35: ["English", "Dutch", "German"],
question36: ["Operations", "Unemployed"],
question37: ["None"],
question38: ["None"],
question39: ["Health & Beauty", "Clothing & Shoes", "Books", "None"],
question40: ["Whatsapp", "Youtube", "Instagram", "None"],
question41: [
"TV (Local/Cable News Broadcast)",
"TV (Late Night Comedy, Other)",
"Radio (AM/FM, Internet, Satellite)",
"Print (Newspapers & Periodicals)",
"None",
],
},
];
This is the function computeData which I used to map over the array and then apply reduce() twice in order to get the object in the format I need. filters is an array which contains the keys of the final object. I am aware this is not the most efficient manner to do so, therefore I need help with improving this and not using reduce() twice in function computeData.
const filters = [
"name",
"longitude",
"latitude",
"agreeableness",
"openness",
"neuroticism",
"extraversion",
"conscientiousness",
"angry",
"fear",
"joy",
"sadness",
"love",
"country",
"question1",
"question2",
"question3",
"question4",
"question5",
"question6",
"question7",
"question8",
"question9",
"question10",
"question11",
"question12",
"question13",
"question14",
"question15",
"question16",
"question17",
"question18",
"question19",
"question20",
"question21",
"question22",
"question23",
"question24",
"question25",
"question26",
"question27",
"question28",
"question29",
"question30",
"question31",
"question32",
"question33",
"question34",
"question35",
"question36",
"question37",
"question38",
"question39",
"question40",
"question41",
];
const computeData = ({ records } = {}) => {
return (
records &&
records.map(({ _fields }) => {
const screenName = _fields[0];
const country = _fields[2][0];
const userPersonality = filters.reduce((acc, curr, idx) => {
if (idx === 0) {
acc[curr] = screenName;
} else if (idx >= 1 && idx <= 12) {
acc[curr] = parseFloat(_fields[1][idx - 1]);
} else if (idx === 13) {
acc[curr] = country;
}
return acc;
}, {});
const questions = _fields[3];
const finalResults = filters.reduce((acc, curr, idx) => {
if (idx > 13) {
questions[idx - 14]
? (acc[curr] = questions[idx - 14])
: (acc[curr] = []);
}
return acc;
}, userPersonality);
return finalResults;
})
);
};
Given the array of responses, you can map them to an array of entries for the new object by using the index parameter in .map and concatenating with 'question'. Then pass the result to Object.fromEntries.
The other properties like "Longitude:5.1193" can be split on : and also be passed to Object.fromEntries.
const result={records:[{keys:["names","value","country","questions"],length:4,_fields:["123ilSE",["Longitude:5.1193","Latitude:52.3246","Agreeableness:0.147083333333333","Openness:0.211041666666667","Neuroticism:0.168833333333333","Extraversion:0.150291666666666","Conscientiousness:0.187041666666666","Angry:0.0441711768507957","Fear:0.020498564466834","Joy:0.875858068466186","Sadness:0.0477884039282798","Love:0.00839435961097478"],["Netherlands","Netherlands"],[["Right"],["Student Loan","None"],["Not at all, i’d rather rent all assets."],["Another benefit"],["Every two weeks","Yearly a few times"],["None","1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["Two to Three Times a Week"],["1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["None","1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["Every two weeks","Yearly a few times"],["Two to Three Times a Week"],["Every Year"],["Banking & Financial Services","Unemployed"],["I don't have a car"],["Netherlands","Netherlands"],["3 - 4 persons"],["Maybe, it depends if nothing betters comes up"],["Desktop"],[],["I don't drive or have a car"],["E, I can be found on social media platforms and maintain my profile but do little else."],["None","Healthcare Insurance"],["None","Hockey","Hiking"],["Hiking"],["Unemployed"],["1999-09-20 00:00:00"],["Female"],["Bachelor's degree"],["Less then 20.000 EUR"],["Single"],["Netherlands","Netherlands"],["1399"],["Prolific Participant"],["English","Dutch","German"],["Operations","Unemployed"],["None"],["None"],["Health & Beauty","Clothing & Shoes","Books","None"],["Whatsapp","Youtube","Instagram","None"],["TV (Local/Cable News Broadcast)","TV (Late Night Comedy, Other)","Radio (AM/FM, Internet, Satellite)","Print (Newspapers & Periodicals)","None"]]]}]};
const [name, otherProps, [country], responsesArr] = result.records[0]._fields;
const output = {
name,
...Object.fromEntries(otherProps.map(str => {
const [key, val] = str.split(':');
return [key, Number(val)];
})),
country,
...Object.fromEntries(responsesArr.map(
(responses, i) => ['question' + (i + 1), responses]
))
};
console.log(output);

Remove objects from array comparing with another array

I have an array blackList where I store blacklisted business names, now I have a results array of objects with many business, I want to store in an array the business names which are not included in the blackListed array, what is the easier and most performant way to do this?
Is a nested loop really needed for this?
blackList = [ "Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company" ,
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao" , "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"],
list = [ { name:'business 1' }, { name:'business 2' }, { name:'business 3' } ]
The easiest way to do this is to use filter and destructuring:
const blackList = ["Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company",
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao", "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"
];
const list = [{
name: 'business 1'
}, {
name: 'business 2'
}, {
name: 'business 3'
}, {
name: "Granier"
}];
const notOnBlacklist = list.filter(({ name }) => !blackList.includes(name));
console.log(notOnBlacklist);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Try
let blackList =
{"Dominos Pizza":1, "Domino's Pizza":1, "McDonald's":1, "McDonalds":1
,"Telepizza":1, "Subway":1, "Burger King":1, "KFC":1, "Pans&Co":1
,"Pans&Company":1, "Rodilla":1, "Rodilla Campamento":1, "Granier":1
,"Llaollao":1, "Taco Bell":1, "Wendy's":1, "Dunkin' Donuts":1, "Pizza Hut":1
,"Papa John's Pizza":1, "Little Caesars":1, "Panera Bread":1, "Chipotle":1
,"Papa Murphy's":1, "Hungry Howie":1, "Chipotle Mexican Grill":1
,"Starbucks":1 };
let list = [];
addBusiness("'business 1'");
addBusiness("Domino's Pizza");
addBusiness("'business 2'");
addBusiness("Hungry Howie");
addBusiness("'business 3'");
console.log(list);
function addBusiness (name) {
if (blackList.hasOwnProperty(name)) return;
list.push({'name':name});
}

How to match values from different array of objects based on a property?

I have two separate arrays of objects. How can I match properties in one array of objects to another property in the second array?
I need to match the cars use in the const cars with the searchingUse in the const buyers.
const cars = [
{ model:convertible,
year:2015,
use:sports
},
{ model:wagon,
year:2013,
use:family
}
]
const buyers =[
{ name:John
searchingUse: family,
maxYear: 2014,
maxPrice:15000
},
{ name: Mark
searchingUse: sedan,
maxYear: 2012,
maxPrice:1000
}
]
The expected output would be a string listing all the cars that match with each buyers desired use
I greatly appreciate any help!
Thanks
I think you want something like this:
const cars = [
{ model: "convertible", year: "2015", use: "sports" },
{ model: "wagon", year: "2013", use: "family" }
];
const buyers = [
{ name: "John", searchingUse: "family", maxYear: "2014", maxPrice: "15000" },
{ name: "Mark", searchingUse: "ddd", maxYear: "2012", maxPrice: "1000" }
];
const a = buyers
.map(buyer => ({
[buyer.name]: cars.filter(car => car.use === buyer.searchingUse)
}));
console.log(a);

(ES6) Filter data with an input field (min.array)

I'm working on a website where you can search for music. I want to put a filter option where people can filter on minimum age.
This is my JSON file:
{
"artists":[
{
"name": "Martin Garrix",
"origin": "Netherlands",
"age": "22 years old",
"artist_id": "c0dc129d8a886a2c9bf487b826c3614a6630fb9c",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Armin van Buuren",
"origin": "Netherlands",
"age": "41 years old",
"artist_id": "8b0a178ce06055312456cccc0c9aa7679d8054f1",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Don Diablo",
"origin": "Netherlands",
"age": "38 years old",
"artist_id": "178c6e7e3bf24710d4895048586a86f1bb81d842",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "David Guetta",
"origin": "France",
"age": "50 years old",
"artist_id": "c2714423228a8012ad37af0186447cbb7ff589f7",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Alesso",
"origin": "Sweden",
"age": "26 years old",
"artist_id": "69fa09f6e181093fe0ea2ce1a4099066509f7837",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
}
]
}
And this is my HTML:
<div class = "div-age">
<label for="age-select">Minimum age</label>
<input type="text" class = "search-age">
</div>
So for example; If you put 40 in the input field, you only get "Armin van Buuren" and "David Guetta".
This is what I have right now.
document.querySelector(`.search-age`).addEventListener(`keyup` , e => {
const term = e.target.value.toLowerCase();
const ageList = document.getElementsByClassName(`artist-info`);
Array.from(ageList).forEach(function(ageList) {
const artistAge = ageList.querySelector(`.age`).textContent;
if (artistAge.toLowerCase().includes(term)) {
ageList.style.display = `flex`;
} else {
ageList.style.display = `none`;
}
})
});
The problem I have now, is that it only filter the exact number. So for example, I put 22, I only get "Martin Garrix"
with filter(), you can do the following way:
const input = {
artists: [
{
name: 'Martin Garrix',
origin: 'Netherlands',
age: '22 years old',
artist_id: 'c0dc129d8a886a2c9bf487b826c3614a6630fb9c',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Armin van Buuren',
origin: 'Netherlands',
age: '41 years old',
artist_id: '8b0a178ce06055312456cccc0c9aa7679d8054f1',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Don Diablo',
origin: 'Netherlands',
age: '38 years old',
artist_id: '178c6e7e3bf24710d4895048586a86f1bb81d842',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'David Guetta',
origin: 'France',
age: '50 years old',
artist_id: 'c2714423228a8012ad37af0186447cbb7ff589f7',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Alesso',
origin: 'Sweden',
age: '26 years old',
artist_id: '69fa09f6e181093fe0ea2ce1a4099066509f7837',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
],
};
const minAge = 40;
const output = input.artists.filter(cur => minAge < parseInt(cur.age));
console.log(output);
You may try to convert the age string to corresponding number using parseInt and then compare it to the value:
// Convert term and artist's age to corresponding integers
term = parseInt(term, 10);
artistAge = parseInt(artistAge, 10);
if (artistAge >= term) {
ageList.style.display = `flex`;
} else {
// ...
}
A couple of things:
you don't need Template literals, you can just use plain string.
Don't use keyup, use input instead as event for such things: it also get things if the user paste the value using a different device than keyboard – e.g. mouse.
Don't use getElementsByClassName since it returns a live HTMLCollection. Use querySelectorAll instead, that returns a static NodeList. It also supports forEach directly, so you don't need to use Array.from.
Don't shadowing the variable, as ageList in the code you wrote, for example: it can lead to unexpected bugs.
Said that:
// you might not want to query all the time this list,
// every time the user change the input value.
const ageList = document.querySelectorAll('.artist-info');
document.querySelector('.search-age').addEventListener('input' , e => {
// no need to lowercase, it's numeric.
// you might want to add some check or constraint on
// <input> validation
const term = +e.target.value;
ageList.forEach(node => {
const artistAge = node.querySelector('.age').textContent;
node.style.display = parseInt(artistAge, 10) >= term ? 'flex' : 'none';
})
});

Categories