1

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)

2
  • What is not working exactly? Is there an error you can provide us? From the looks of it, it should raise said error, the data you provided is not valid JSON.(additionalData cannot be properly parsed, you need to replace all double quotes by single quotes between your former double quote, or vice-versa). Commented Jan 12, 2022 at 15:27
  • I'm fetching from an API so can't change the strings. I want in the template to be able to just write parseText(payment) instead of writing JSON.parse(note.additionalData).payment :) When I write .type after like I do, it only says that type is declared but value never read Commented Jan 12, 2022 at 15:29

1 Answer 1

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)
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.