filter function shows an empty array - javascript

I want to create a search filter. The way it works is a user inputs a text in the search bar, the input is stored using vuex and the result is shown in a different page. Here's an array of objects in a js file
export const productData = [
{
id: 1,
name: "table",
materials: "wood"
},
{
id: 2,
name: "table2",
materials: "metal"
},
{
id: 3,
name: "chair",
materials: "plastic"
}
]
I want to filter using the user's input. Here's my function
import { productData } from '#/data/productData'
export default {
data() {
return {
products: productData
}
},
computed: {
userInput() {
return this.$store.state.userInput
},
filterProducts: function() {
return this.products.filter(q => q.name.match(this.userInput))
}
}
}
When I console the userInput, it works fine! So the problem is in the filterProducts function. It shows an empty array if I console it. What am I doing wrong? Thank you.
edit: the reason I make a new variable called products is because the actual js file is more complex so I had to flatten the array. But the flatten process works fine so I thought I would just simplify the question.

The match function accepts a regex, not String. Give indexOf a try:
filterProducts: function() {
return this.products.filter(q => q.name.indexOf(this.userInput) >= 0)
}

Related

Maintaining react state with a hierarchical object using react hooks (add or update)

I have an a state object in React that looks something like this (book/chapter/section/item):
const book = {
id: "123",
name: "book1",
chapters: [
{
id: "123",
name: "chapter1",
sections: [
{
id: "4r4",
name: "section1",
items: [
{
id: "443",
name: "some item"
}
]
}
]
},
{
id: "222",
name: "chapter2",
sections: []
}
]
}
I have code that adds or inserts a new chapter object that is working. I am using:
// for creating a new chapter:
setSelectedBook(old => {
return {
...old,
chapters: [
...old.chapters,
newChapter // insert new object
]
}
})
And for the chapter update, this is working:
setSelectedBook(old => {
return {
...old,
chapters: [
...old.chapters.map(ch => {
return ch.id === selectedChapterId
? {...ch, name: selectedChapter.name}
: ch
})
]
}
})
But for my update/create for the sections, I'm having trouble using the same approach. I'm getting syntax errors trying to access the sections from book.chapters. For example, with the add I need:
// for creating a new section:
setSelectedBook(old => {
return {
...old,
chapters: [
...old.chapters,
...old.chapters.sections?
newSection // how to copy chapters and the sections and insert a new one?
]
}
})
I know with React you're supposed to return all the previous state except for what you're changing. Would a reducer make a difference or not really?
I should note, I have 4 simple lists in my ui. A list of books/chapters/sections/items, and on any given operation I'm only adding/updating a particular level/object at a time and sending that object to the backend api on each save. So it's books for list 1 and selectedBook.chapters for list 2, and selectedChapter.sections for list 3 and selectedSection.items for list 4.
But I need to display the new state when done saving. I thought I could do that with one bookState object and a selectedThing state for whatever you're working on.
Hopefully that makes sense. I haven't had to do this before. Thanks for any guidance.
for adding new Section
setSelectedBook( book =>{
let selectedChapter = book.chapters.find(ch => ch.id === selectedChapterId )
selectedChapter.sections=[...selectedChapter.sections, newSection ]
return {...book}
})
For updating a section's name
setSelectedBook(book=>{
let selectedChapter = book.chapters.find(ch => ch.id === selectedChapterId )
let selectedSection = selectedChapter.sections.find(sec => sec.id === selectedSectionId )
selectedSection.name = newName
return {...book}
})
For updating item's name
setSelectedBook(book =>{
let selectedChapter = book.chapters.find(ch => ch.id === selectedChapterId )
let selectedSection = selectedChapter.sections.find(sec => sec.id === selectedSectionId )
let selectedItem = selectedSection.items.find(itm => itm.id === selectedItemId)
selectedItem.name = newItemName
return {...book}
})
I hope you can see the pattern.
I think the map should work for this use case, like in your example.
setSelectedBook(old => {
return {
...old,
chapters: [
...old.chapters.map(ch => {
return { ...ch, sections: [...ch.sections, newSection] }
})
]
}
})
In your last code block you are trying to put chapters, sections and the new section into the same array at the same level, not inside each other.
Updating deep nested state objects in React is always difficult. Without knowing all the details of your implementation, it's hard to say how to optimize, but you should think hard about different ways you can store that state in a flatter way. Sometimes it is not possible, and in those cases, there are libraries like Immer that can help that you can look in to.
Using the state object you provided in the question, perhaps you can make all of those arrays into objects with id for keys:
const book = {
id: "123",
name: "book1",
chapters: {
"123": {
id: "123",
name: "chapter1",
sections: {
"4r4": {
id: "4r4",
name: "section1",
items: {
"443": {
id: "443",
name: "some item"
}
}
}
}
},
"222": {
id: "222",
name: "chapter2",
sections: {},
}
]
}
With this, you no longer need to use map or find when setting state.
// for creating a new chapter:
setSelectedBook(old => {
return {
...old,
chapters: {
...old.chapters,
[newChapter.id]: newChapter
}
}
})
// for updating a chapter:
setSelectedBook(old => {
return {
...old,
chapters: {
...old.chapters,
[selectedChapter.id]: selectedChapter,
}
}
})
// for updating a section:
setSelectedBook(old => {
return {
...old,
chapters: {
...old.chapters,
[selectedChapter.id]: {
...selectedChapter,
sections: {
[selectedSectionId]: selectedSection
}
},
}
}
})
Please let me know if I misunderstood your problem.

watch changes of nested data in vuejs

I want to watch changes of families variable which contains nested objects
<component-test
v-for="family of familiesToDisplay"
// rest
/>
data: () => ({
families: [],
}),
computed: {
familiesToDisplay() {
return this.families.fillter(family => family.members > 4);
},
},
In some response I have seen some recomanding the use of watch but in my case I didn't knew how to implement it since I have never used before.
so the request is to get changes of nested objects in families (as objects I have person and work so if a name of a person has been changed or its work has been changed changes must be retreived here)
This code should work fine, however, it is necessary to correctly mutate objects inside an array. You need to use this.$set or replace the object with a new one to trigger vue re-rendering a list and recalculation of a list.
For example, you can change them like this, (full working example you can find here):
export default {
name: "HelloWorld",
components: {
Display,
},
data: () => ({
families: [
{ name: "foo-1", members: 1 },
{ name: "foo-5", members: 5 },
{ name: "bar-6", members: 6 },
{ name: "bar-3", members: 3 },
],
}),
methods: {
onClick() {
this.families.forEach((family) => {
this.$set(family, "members", this.getRandomNumber());
});
},
getRandomNumber() {
return Math.floor(Math.random() * 10) + 1;
},
},
};

loop through an array and choose specific to setstate

New react developer here, here i have two API's, first one gives an object :
{ id: "98s7faf", isAdmin: true, name: "james"}
second one gives an array of objects :
[
{ billingName: "trump", driverName: "james" },
{ billingName: "putin", driverName: "alex" },
{ billingName: "kalle", driverName: "james" },
{ billingName: "sussu", driverName: "trump" },
{ billingName: "vladimir", driverName: "james" },
]
my question is, when user goes to the page, the page should automatically check both API'S, from first api name and from second api driverName, and if those two have same value then take that specific object from an array and pass it to these:
setOrders(res);
setRenderedData(res);
so at the moment there are three objects (those which have value of james) inside an array which matches name from first api, so it should pass those, and the rest which have different value it should not let them pass. here is my code, what have i done wrong ? instead of some(({ driverName }) i need some kind of filter ?
useEffect(() => {
api.userApi.apiUserGet().then((res1?: User ) => {
return api.caApi.apiCaGet(request).then((res?: CaDto[])
=> {
if (res.some(({ driverName }) => driverName === res1?.name)) {
setOrders(res);
setRenderedData(res);
console.log(res);
}
});
});
}, [api.caApi, api.userApi]);
you need to filter your response to extract the right objects given your condition.
useEffect(() => {
api.userApi.apiUserGet().then((res1?: User ) => {
return api.caApi.apiCaGet(request).then((res?: CaDto[])
=> {
const filteredData = res?.filter(({ driverName }) => driverName === res1?.name);
if(filteredData?.length) {
setOrders(filteredData);
setRenderedData(filteredData);
console.log(filteredData);
}
});
});
}, [api.caApi, api.userApi]);
note: having 2 states that holds the same values (orders, renderedData) is not a good practice, you might consider to refactor your logic.

Vue computed property changes the data object

I have basically this structure for my data (this.terms):
{
name: 'First Category',
posts: [
{
name: 'Jim James',
tags: [
'nice', 'friendly'
]
},
{
name: 'Bob Ross',
tags: [
'nice', 'talkative'
]
}
]
},
{
name: 'Second Category',
posts: [
{
name: 'Snake Pliskin',
tags: [
'mean', 'hungry'
]
},
{
name: 'Hugo Weaving',
tags: [
'mean', 'angry'
]
}
]
}
I then output computed results so people can filter this.terms by tags.
computed: {
filteredTerms: function() {
let self = this;
let terms = this.terms; // copy original data to new var
if(this.search.tags) {
return terms.filter((term) => {
let updated_term = {}; // copy term to new empty object: This doesn't actually help or fix the problem, but I left it here to show what I've tried.
updated_term = term;
let updated_posts = term.posts.filter((post) => {
if (post.tags.includes(self.search.tags)) {
return post;
}
});
if (updated_posts.length) {
updated_term.posts = updated_posts; // now this.terms is changed even though I'm filtering a copy of it
return updated_term;
}
});
} else {
return this.terms; // should return the original, unmanipulated data
}
}
},
filteredTerms() returns categories with only the matching posts inside it. So a search for "angry" returns just "Second Category" with just "Hugo Weaving" listed.
The problem is, running the computed function changes Second Category in this.terms instead of just in the copy of it (terms) in that function. It no longer contains Snake Pliskin. I've narrowed it down to updated_term.posts = updated_posts. That line seems to also change this.terms. The only thing that I can do is reset the entire data object and start over. This is less than ideal, because it would be loading stuff all the time. I need this.terms to load initially, and remain untouched so I can revert to it after someone clears their search criterea.
I've tried using lodash versions of filter and includes (though I didn't really expect that to make a difference). I've tried using a more complicated way with for loops and .push() instead of filters.
What am I missing? Thanks for taking the time to look at this.
Try to clone the object not to reference it, you should do something like :
let terms = [];
Object.assign(terms,this.terms);
let terms = this.terms;
This does not copy an array, it just holds a reference to this.terms. The reason is because JS objects and arrays are reference types. This is a helpful video: https://www.youtube.com/watch?v=9ooYYRLdg_g
Anyways, copy the array using this.terms.slice(). If it's an object, you can use {...this.terms}.
I updated my compute function with this:
let terms = [];
for (let i = 0; i < this.terms.length; i++) {
const term = this.copyObj(this.terms[i]);
terms.push(term);
}
and made a method (this.copyObj()) so I can use it elsewhere. It looks like this:
copyObj: function (src) {
return Object.assign({}, src);
}

Bootstrap-vue multiselect data binding: infinite loop

I'm trying to setup a multi select control from bootstrap-vue and bind it to a JSON object. The problem is that I need a computed value to get my json data format in a int array for the multiselect selected values and vice versa. Using such a computed property means that I change date while rendering which leads to an infinite loop.
Currently I created a computed property which has a getter which transforms the JSON object array in a integer array as well as a setter which does the opposite. In my example code the JSON object only contains the id, but in my production code there are a lot of other fields inside a "company".
<template>
<b-form>
<b-form-select
:id="`input-companies`"
v-model="companiesSelected"
multiple
:select-size="4"
:options="availableCompanies"
></b-form-select>
</b-form>
</template>
<script>
const availableCompanies = [
{ value: 1, text: 'company1' },
{ value: 2, text: 'company2' },
{ value: 3, text: 'company3' },
{ value: 4, text: 'company4' }
]
export default {
data () {
return {
employee: { id: 1, name: 'test', companies: [ { id: 1 }, { id: 2 } ] },
availableCompanies: availableCompanies
}
},
computed: {
companiesSelected: {
get () {
if (this.employee.companies == null) {
return []
}
return this.employee.companies.map(company => { return company.id } )
},
set (newValue) {
if (newValue == null) {
this.employee.companies = []
} else {
this.employee.companies = newValue.map(companyId => { return { id: companyId } })
}
}
}
}
}
</script>
The setting of this.employee.companies leads to a infinite loop. I don't really know how to avoid this. Does anyone know how to overcome this issue?
I basically split your computed set into the #change event and it seems to be working.
The #change event should only fire from user interactivity and should therefor cause the loop.
https://codepen.io/Hiws/pen/agVyNG?editors=1010
I'm not sure if that's enough for you, as i didn't take the extra fields on a company into consideration when writing the example above.

Categories