I would like to create a simple web apps that can display all json data and user can filter it?
here it my code I am using Vue 2
index.html
<div id="app">
<input type="input" id="txt-search" v-model="mySearch">
<select>
<option :value="post.id" v-for="post in searchBook"
>{{post.id}}</option>
</select>
</div>
script.js
var json_data = 'jsonfile.json'
var app = new Vue({
el: '#app',
data: {
posts: null,
mySearch:''
},
created: function () {
this.fetchData()
},
methods: {
fetchData: function () {
var xhr = new XMLHttpRequest()
var self = this
xhr.open('GET', json_data)
xhr.onload = function () {
self.posts = JSON.parse(xhr.responseText)
}
xhr.send()
}
},
computed: {
searchBook() {
return this.mySearch ? this.posts.filter(post => {
return post.title.includes(this.mySearch);
})
: this.posts;
}
}
})
It only filter title data
post.title.includes(this.mySearch)
Is it posible to filter all json data like
post.*.includes(this.mySearch)
CodePudding user response:
function filterArray(arr, keyword) {
if (!keyword) return arr;
return arr.filter(obj =>
Object.values(obj)
.some(value => typeof value === 'string' && value.includes(keyword))
);
}
Usage:
computed: {
searchBook() {
return filterArray(this.posts, this.mySearch);
}
}
CodePudding user response:
It is but is a little complicated. First, you must extract all the values from the object and filter every record to check if it contains the searched phrase.
Example:
const posts = [
{title: 'title1', author:'author1', comment: 'comment1'},
{title: 'foo', author:'author2', comment: 'comment2'},
{title: 'title3', author:'bar', comment: 'comment3'},
]
const serchedPhrase = 'author';
const filteredData = posts.filter((e) => {
const values = Object.keys(e).map(val => e[val]);
const filteredValues = values.filter((el) => el.includes(serchedPhrase));
return filteredValues.length > 0;
});
console.log(filteredData);