By using asyncdata and axios I am grabbing a json object from a database called Knack.
Working great however the whole response is huge and in some pages I’m only using say 10 fields from sometimes 50 .
So I’m grabbing records from knack and then using v-for to loop through and output 10 of the 50 fields from say 200 records.
By looking in console I can see the whole json object.
Is there a way to get the json object as I am and rather than returning it all, loop through and create a smaller object with the fields I need and returning that to then do a v-for in my template? Basically resulting in only the required fields being visible in console and to the public?
Thanks so much if someone can help with a code sample.
CodePudding user response:
You can do that in a computed property.
computed(){
getCustomObject(){
let customObject = {};
for(let property in yourJsonObject){
if(property == 'the field you want'){
customObject[`${property}`] = yourJsonObject[property]
}
}
return customObject;
}
}
In this way you can get specific fields that you want. But you will have to specify them by placing ||
in the if
statement.
In template you can simply render it like this: -
<div v-for="(item,key,index) in getCustomObject" :key="index">
//Render data...
</div>
Or if you just want a specific number of fields like 10 fields from 50, you can do it like this: -
computed(){
getCustomObject(){
let customObject = {};
Object.entries(yourJsonObject).forEach(([key,value],index) => {
if(index<10){
customObject[`${key}`] = value;
}
})
return customObject;
}
}
CodePudding user response:
Try with object destructuring:
const jsonObject = { f1: 1, f2: 2, f3: 3, f4: 4, f5: 5, f6: 6, f7: 7, f8: 8, f9: 9, f10: 10};
const neededFields = (({ f2, f5, f7 }) => ({ f2, f5, f7 }))(jsonObject);
console.log(neededFields);