How to filter array in json object with computed - vue.js

fetchData() {
axios.get("api_url").then((response) => {
this.dataArr = response.data;
});
},
I can't do this.dataArr = response.data.items.fruits; because I need to use this somewhere else like this.
dataArr looks like this:
{
"items":{
"fruits":[
{
"name":"banana",
"type":"fruit",
},
{
"name":"kiwi",
"type":"fruit",
},
]
}
I am trying to filter this in computed property:
filterData(){
return this.dataArr.filter((item) => item.name )
}
But I am getting an error saying that this.dataArr is not a function, I need to get access to this.dataArr.items.fruits, but when I write it like that it's not working. Is there way to solve this?

You should get access to the nested fruits array and it seems that you're trying to map that array by returning only the names in this case use map method:
filterData(){
if(this.dataArr.items && this.dataArr.items.fruits){
return this.dataArr.items.fruits.map((item) => item.name )
}else{
return []
}
}

Related

Vuex passing different arrays

Making a filter:
Mutations
export default {
state: {
filteredBrands: []
},
mutations: {
showFilteredList(state, payload) {
state.filteredBrands.push(payload);
}
}
};
Methods
loadProducts(item) {
axios.get('/api', {
params: {
per_page: 20,
filter_machinery_brands: [ item ]
}
})
.then((response) => {
this.$store.commit(
'showFilteredList',
response.data
);
});
},
item this is an input with a checkbox, when clicked, a request is made to the server for this category
For some reason, the push does not work, why?
And I would like there to be a check, if the array is the same, then delete, otherwise add. Is it possible?
If you can se an array comes in as payload. Then you are trying to push an array into an array. Which cant be done in either js or ts.
You can try set the value:
state.filteredBrands = payload;
otherwise you would have to do something like this:
state.filteredBrands.push(payload[0]);
If you wanna control for existing items in array, and assuming your are not always setting value, but pushing new values into your array. You can do something like this:
if (state.filteredBrands.indexOf(payload[0]) === -1) {
// Not in array
state.filteredBrands.push(payload[0])
} else {
// is allready in array
state.filteredBrands.forEach((item, index) => {
if (item === payload[0]) {
state.filteredBrands.splice(index, 1)
}
})
}
EDIT:
My assumption was right.
Your payload is an array
Your state is an array
-------> You are trying to push payload(array) into state(array) - which cant be done i js - This solution would after my suggestion be more clean:
payload.forEach((value, index) => { // Looping payload
if (state.filteredBrands.indexOf(value) === -1) {
state.filteredBrands.push(value) // push if value not allready in array
} else {
state.filteredBrands.splice(index, 1) // if value is in array -> remove
}
})
Yes, you can push an array into an array.
I guess the problem here is your vuex config.
Vuex state is a function, so it needs to be:
state () {
return {
filteredBrands: []
}
}
And if you are using Nuxt:
export const state = () => ({
filteredBrands: []
})

Vue: Add items to computed property results which do not exist my Array of Objects

I have a computed property that filters the results on the date:
resultfilteredResults() {
const filteredResults = this.results.filter((result) => {
return Date.now() < new Date(result.metaData.E);
});
return filteredResults;
},
That works fine.
Now I have realized that my filteredResults need to contain data that does not necessarily exist in the specific Object.
For example. One bit of data within the object in the Array looks like this:
"C": "Pakistan, Vietnam, Wales, Western Sahara, Yemen, Zambia"
Sometimes "C" will not exist (when this is the case it means it should bring back all available data in all "C" objects within the whole Array. This is because it is not only for specific counties but all countries. I hope that makes sense.
I tried this but it does not work.
resultfilteredResults() {
const undefinedResults = result.metaData;
{
const filteredResults = this.results.filter((result) => {
return Date.now() < new Date(result.metaData.E);
});
if (undefinedResults == "undefined") {
return undefinedResults;
} else {
return filteredResults;
}
}
},
Can anyone help?
There is nothing wrong with the code.
What is not clear is if (undefinedResults == "undefined") {
undefinedResult is a string "undefined"? or just undefined?
Can you try this?
if (undefinedResults == undefined) {

Using set() for computed values correctly in Vue

I'm having an issue with setting a computed property (which is an array). I have the following computed property in my Vue component:
posts: {
get () {
if ( this.type == 'businesses' || this.type == 'business' ) {
return this.$store.getters.getAllBusinesses.map(_business => {
return _business
})
} else if ( this.type == 'shops' || this.type == 'shop' ) {
return this.$store.getters.getAllShops.map(_shop => {
return _shop
})
} else if ( this.type == 'events' || this.type == 'event' ) {
return this.$store.getters.getAllEvents.map(_event => {
return _event
})
} else {
return this.$store.getters.getAllBusinesses.map(_business => {
return _business
})
}
},
set (posts) {
console.log(posts)
this.posts = posts // Doesn't work - this causes a maximum call stack error, recursively setting itself obviously.
return posts // Doesn't work either - this.posts doesn't seem to be changing...
}
},
The console.log(posts) is exactly what I want - a filtered array of posts, see the below console log output.
My question is simply this: how do I go about updated the computed posts value?
If it is useful, I am doing the following manipulation to the posts:
let filteredPosts = []
this.posts.filter(_post => {
_post.category.forEach(category => {
if ( this.categoryFilters.includes(category.slug) ) {
filteredPosts.push(_post)
}
})
})
let uniqueFilteredPosts = [...new Set(filteredPosts)];
this.posts = uniqueFilteredPosts
This is purely to filter them. What I am console.logging is absolutely correct to what I want. So this might be a red herring.
Any pro-Vue tips would be greatly appreciated!
If you want to use a computed setter, you normally assign to whatever values underlie the computed's get function. See the example at the link.
In your case, you examine this.type and return something from the store based on it. The setter should probably examine this.type and set something in the store based on it.

Lodash chaining issue

I am having trouble getting the value of my chain. I believe it has something to do with the returns in my code.
let wrapper = _.chain($scope.meetings)
.orderBy($scope.meetings, function(o) { return new moment(o.meetingDate); }, ['asc'])
.filter($scope.meetings, function(o) { return moment(o.meetingDate).isAfter(begin) && moment(o.meetingDate).isBefore(end); })
.forEach($scope.meetings, function(o) { o.createdBy = $scope.myData[0].fullName;})
.value();
I am getting an empty array as the value
as #gruff-bunny said, solve was to remove the variable from my orderBy, filter, and forEach. In the end, my function looks like this.
$scope.meetings = _.chain($scope.meetings)
.orderBy(function(o) { return new moment(o.meetingDate); }, ['asc'])
.filter(function(o) { return moment(o.meetingDate).isAfter(begin) && moment(o.meetingDate).isBefore(end); })
.value();

How to populate empty array with a method in Vue

I'm trying to populate an empty array with a declared array variable in a computed function. I tried this but with no luck:
data: {
hashtags: []
},
computed: {
filteredHashtags () {
var defaultHashtags = [ '#hr', '#acc', '#sales' ];
var fHashtags =
_.chain( messages )
.pluck( 'hashtags' )
.flatten()
.map(
function ( tag ) {
return tag && tag.trim() ? '#' + tag : null; })
.filter( Boolean )
.value();
fHashtags = _.union( fHashtags, defaultHashtags );
return data.hashtags = fHashtags;
}
}
also, is there a better method to approach this?
A computed property isn't really a good use case for this, because the computed value has to be referenced in order for it to be called. Instead, just make it a method and call it the method when your Vue is created.
data: {
hashtags: []
},
methods: {
filterHashtags() {
// commented out stuff
// set the data property with the filtered values
this.hashtags = fHashtags;
}
},
created(){
this.filterHashtags();
}