show result List as per count - javascript

Like here, I want the number of times it has in registration array, I want to show it in a single row. Currently its like below, But I want it like if there's 2 result then I want it 2 time in a single row.
So here if you check the prototype(of item), You can see 2 count, so i want to show 2 results, along sides.
const title = responseData.map(item => {
return { label: `${item.title} (${item.registration[0].registration_type.code}) (${item.registration.length.toString()})`, value: item._id };
});

I am assuming the data you want in each row is all stored inside each element in the item.registration array.
const title = responseData.map(item => {
// map all the values inside the registration on to an array of labels
const labels = item.registration.map(registration => {
return `${item.title} (${registration.registration_type.code})`;
})
// Join the labels created above with a comma separating them
return { label: labels.join(', '), value: item._id };
});

Related

How to remove number ( item ) from array and show only strings? using vanilla js

i got results:
link https://api/v1/3
link https://api/v1/3/user
link https://api/v1/3/customer
link https://api/v1/3/suppliers
i am filtering this results and show only
3, user, customer, suppliers
but i want to show only
user, customer, suppliers
I want to remove 3... in loop this 3 in seconds interation will be 2 or any other number..
My try
const result = obj.links.map((o) => o.href.split("/").pop());
and
const result = obj.links.map((o) => o.href.replace(/.*(?=\/)/, "").slice(1));
but in both case i print 3 ...
i want to show only :
user, customer, suppliers
You can use Array.prototype.reduce along with a check if the element popped loosely equals itself cast to a Number.
const links = [{"href": "https://api/v1/3"},{"href": "https://api/v1/3/user"},{"href": "https://api/v1/3/customer"},{ "href": "https://api/v1/3/suppliers"}];
const result = links.reduce((acc, {href: link}) => {
const last = link.split('/').pop();
if (!(last == Number(last))) acc.push(last);
return acc;
}, []);
console.log(result);
You could achieve the same with a map followed by a filter, but that would have to iterate your array twice.

How do i search for a particular value from an array of objects?

I have an array of objects called 'Tags' of type :
type Tag = {
id: number,
label: string
}
Below is some sample data inside it.
const [tags, setTags] = useState<Tag[]>([{id: 1, label: "random"}, {id: 2, label: "important"}, {id: 3, label: "ignore"}])
I have an input field which takes input and sets it to "input" state on change.
I want to display a paragraph element only if the searched input field doesn't exist inside the tags.
I was unable to find a way to directly search it as the tags array is made of objects and i want to search that object's label property.
So i ended up doing something like this...
{tags.map(tag => {
if(!(tag.label.toLowerCase().includes(input.toLowerCase()))){
return <p>{input}</p>
}
})}
but this would render the paragraph each time the input doesn't match the values. So in this case it renders the paragraph 3 times if i add a new label. I want it to render just once. How do i fix this?
You could use filter to filter tags and then if result has a length > 0 show <p>{input}</p> one time:
return (
{tags.filter(tag => !(tag.label.toLowerCase().includes(input.toLowerCase())).length > 0 &&
<p>{input}</p>
})});
To render the input in a p tag when none of the labels includes it:
const Bla = () => { // assuming Bla is your component
const shouldRenderInput = tags.every(
(tag) => !tag.label.toLowerCase().includes(input.toLowerCase())
);
return <>{shouldRenderInput && <p>{input}</p>}</>;
};
see Array.prototype.every

push dynamically coming id's and value's in javascript

The question may seem a little confusing so let me explain the situation, i have a category field, that when it's chosen, i get data from api based on that category, for example when you choose category A, you may get the id's 1 to 3 or when you chose category B, you get the id's of 8 to 11, so what i'm trying to do is create a Filter array that pushes these values with id's so when user types something like sth in input with the id of 1, this objects gets pushed to the array, something like below:
Filters = [
{
id:1,
value: sth
}
]
so what i have basically done is something like this:
this.props.Filters.map(item => (
<div className="from" key={item.id} id={item.id} >
<span className="title">{item.feature}</span>
<input type="text" placeholder="..." id={item.id} onChange={FilterPush}></input>
</div>
))
and the function is:
const Filters = []
const FilterPush = (e) => {
const filter = {
id: e.currentTarget.getAttribute("id"),
value: e.currentTarget.value
}
Filters.push(filter)
}
the problem i'm having here is every time a user is typing something an object is pushed to Filters,
so when user tries to type sth the Filter gets equal to:
Filters={
{id:1,value:s},
{id:1,value:st},
{id:1,value:sth}
}
but i want it to be equal to this
Filters={
{id:1, value:sth}
}
bear in mind that the id's are dynamic and i don't know them, and there's not just one input, i mean we can have 3 inputs with diffrent id's that should get send to the server.
Just filter out existing id:
const FilterPush = (e) => {
let id = e.currentTarget.getAttribute("id")
const filter = {
id,
value: e.currentTarget.value
}
Filters = Filters.filter(item => item.id !== id) // filter out existing id
Filters.push(filter)
}
It's very simple all you have to do is just check the pushing element's id is already in the Filters array before pushing the element.
const FilterPush = (e) => {
let id = e.currentTarget.getAttribute("id")
const filter = {
id: e.currentTarget.getAttribute("id"),
value: e.currentTarget.value
}
Filters.map(item=>{
if(id == item.id){
available = true;
}
})
if(!available){
Filters.push(filter)
}
}

How to search a value in an array inside another array

I have a problem of find a value in an array inside another array, and use the result to setState()
This is the initialState:
this.state =
{
initialStudents:[
{name:"str1",tags;["str","str",...],...},
{name:"str2",tags;["str","str",...],...},
...
],
students: [
{name:"str1",tags;["str","str",...],...},
{name:"str2",tags;["str","str",...],...},
...
]
}
The code i use to find the tags:
findTag = (tags, target) => {
tags.filter(tag => {
return tag.toLowerCase().search(target.toLowerCase()) !== >-1;
});
};
filterTag = e => {
let updatedList = this.state.initialStudents;
updatedList = updatedList.filter(student => {
return this.findTag(student.tags, e.target.value);
});
this.setState({ students: updatedList });
};
The filterTag does not update the students state
To solve your problem, I made a few edits and put them all in this working codesandbox example.
First, I changed your findTag function to something like this:
// pass in the tags from the student, and the target tag you're searching for.
// -> return true if 1 or more matching tag, false otherwise
findTag = (tags, targetTag) => {
// make sure you return something!
return tags.filter(tag => {
// check if current tag in arr matches target tag (case insensitive)
return tag.toLowerCase() === targetTag.toLowerCase();
}).length > 0; // check if there's 1 or more matching tag
};
Next, I updated the filterTag function in a few ways:
Immutably copy this.state.initialStudents into the local updatedList array. This is necessary so you don't mess up the current state before running this.setState!
Pass the value of the input via this.state.filterTag instead of e.target.value. This way, you'd update the filter when you click the button instead of on every time you press a key.
Here's how these changes look:
filterTag = e => {
// immutably copy initial student data
let updatedList = this.state.initialStudents
.map(student => ({
name: student.name,
tags: [...student.tags]
}))
// remove students w/out filter tag
.filter(student => {
return this.findTag(student.tags, this.state.filterTag);
});
// update state with new student list
this.setState({ students: updatedList });
};
A few other improvements I made:
Instead of manually setting data in initialStudents and students, I made them immutably copy the same data set from the const initialStudents data set. This could be done in the componentDidMount lifecycle method if you're fetching students from a database.
I fixed your student object declarations - you put tags;["str"...] which is invalid - the semicolon ; should be a normal colon :
I changed some "str" values to "str2" to make them unique between students
Let me know if you have questions about the codesandbox or anything else :D Hope it helps!

Trouble with React/JS filter

I am trying to implement a filter function that is able to search in two separate JSON fields when a user types in a search bar. Searching the whole JSON returns errors and if I repeat this function, the two similar functions cancel each other out.
My current filter function:
let filteredOArt = origArt.filter((origAItem) => {
return origAItem.authors.toLowerCase().includes(this.state.search.toLowerCase())
});
I want to be able to have the search look within the "authors" field as well as a "description" field.
Before the React render, I have this function listening to the state:
updateSearch(event) {
this.setState({ search: event.target.value })
}
Then my search function is in an input field in the React return:
<h6>Search by author name: <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} /></h6>
You can tweak the function a bit like this
let filteredOArt = origArt.filter((origAItem) => {
return (
(origAItem.authors.toLowerCase().includes(this.state.search.toLowerCase())||
(origAItem.description.toLowerCase().includes(this.state.search.toLowerCase())
)
)
});
You actually can do a filter for both fields.
Given you have your searchValue and your array with the objects you could filter this way:
const filterByAuthorOrDescription = (searchValue, array) =>
array.filter(
item =>
item.authors.toLowerCase().includes(searchValue.toLowerCase()) ||
item.description.toLowerCase().includes(searchValue.toLowerCase())
);
const filtered = filterByAuthorOrDescription(this.state.search, articles);
filtered will now contain an array of objects that contain your searchValue in either description or authors that you can map through.
You could use some to check if the filter is positive for at least one field :
let filteredOArt = origArt.filter(origAItem => ['authors', 'description'].some(field => origAItem.[field].toLowerCase().includes(this.state.search.toLowerCase())))
Just iterate over the different field names you want to use.
Some will return true if any of the fields mentioned contains your string and avoid repetitions in your code.
Long syntax :
origArt.filter(origAItem => {
return ['authors', 'description'].some(field => origAItem.[field].toLowerCase().includes(this.state.search.toLowerCase()))
})

Categories

Resources