Create JSON.parse method to reuse VUE
So I'm iterating through an array (using Vue). In this array their are objects with strings.
notifications: [
0: {
idType: 1
type: "delivered"
user: 12
visibility: true
seller: 15
product: "phone"
additionalData: "{"type":"iphone","idType":5,"number":"2"}"
}
1: {
idType: 2
type: "meeting"
user: 12
visibility: null
seller: 12
company: "hotell"
additionalData: "{"location":"office","idType":7,"number":"8"}"
}
2: {
idType: 1
type: "invoiced"
user: 15
visibility: null
seller: 11
value: 150000
additionalData: "{"payment":"credit","idType":10,"number":"1"}"
}
]
So I need to parse all the info in the different additionalDatas. It gets kind of messy when I do it for each in the template so I want to create a method for it.
I've tried something like this:
parseText(type: string) {
return JSON.parse(this.note.additionalData).type
},
This obviously doesn't work but can't figure out how to make it work. (sending note to parent component as a prop, and am also doing the v-for in the parent component)
Solution 1:
I'm not sure why the going for method
doesn't work for you but you can also create a component that receives the object as a prop and have a computed property inside that will automatically parse it for you.
<Notification
v-for="notification in notifications
:key="notification.id"
:notification="notification"
/>
props: {
notification: {
required: true,
type: Object,
}
},
computed() {
additionalDataObj() {
return JSON.parse(this.notification.additionalData)
}
}