Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData.

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"}"
  }
]

While parsing all the information from these additionalDatas, it becomes quite messy when done individually for each object in the template. To streamline this process, I intend to create a method for it.

I attempted to create a method like so:

parseText(type: string) {
    return JSON.parse(this.note.additionalData).type
},

Unfortunately, this approach did not yield the desired result. I am currently passing 'note' to the parent component as a prop and also utilizing v-for in the parent component.

Answer №1

It's puzzling why the method approach isn't working for you, but another option is to develop a component that accepts the object as a prop and includes a computed property that automatically parses it.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The pdf generation feature of pdf-creator-node in Linux seems to be malfunctioning

An error occurred with code EPIPE at afterWriteDispatched (internal/stream_base_commons.js:154:25) at writeGeneric (internal/stream_base_commons.js:145:3) at Socket._writeGeneric (net.js:784:11) at Socket._write (net.js:796:8) ...

"Encountering difficulty in retrieving information from $q and integrating it into the

I am facing an issue with binding data from an API to my scope using promises in AngularJS. Despite successfully retrieving the JSON data from the server, the $scope variable remains empty. Any assistance on this matter would be greatly appreciated. Thank ...

Calculating the average of duplicate values in a multidimensional PHP array

I'm in a bit of a pickle trying to add comprehensive product review data to SKU records, particularly getting the average value of duplicated keys. Array ( [0] => Array ( [sku] => 70835 [rating] => 5 ...

"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help... I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML? Here i ...

The UPDATE query failed to make any changes to the data stored in the MySQL

Currently I am developing an application using express.js. In my project, I have incorporated the "mysql" add-on (https://www.npmjs.com/package/mysql). The issue I am facing is while sending an UPDATE query to the server and receiving a response that shows ...

Explaining how to use the describe function in TypeScript for mapping class constructors

I am working on a function that will return a JavaScript Object with the class instances as values and the class names as keys. For example: const init = (constructorMap) => { return Object.keys(constructorMap).reduce((ret, constructorName) => ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...

Attempting to troubleshoot and execute knex commands within the package.json file

At the moment, I am utilizing a knex project that was crafted by an individual on GitHub. I've encountered some issues with the package.json file, which should ideally simplify the execution of knex commands: { "name": "database", "version": "1. ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Utilizing Angular signals to facilitate data sharing among child components

I have a main component X with two sub-components Y and Z. I am experimenting with signals in Angular 17. My query is how can I pass the value of a signal from sub-component Y to sub-component Z? I have attempted the following approach which works initial ...

The attribute 'elements' is not present within the data type 'Chart'

var canvas = document.getElementById("canvas"); var tooltipCanvas = document.getElementById("tooltip-canvas"); var gradientBlue = canvas.getContext('2d').createLinearGradient(0, 0, 0, 150); gradientBlue.addColorStop(0, '#5555FF'); grad ...

methods for merging and flattening arrays in php

Hello, I recently wrote this code in Laravel: return [ 'image' => $this->image, $this->categories()->get()->map(function ($category) { return [ $category->name => $category->pivot->image ...

"Maximizing the slider with jCarousel: A guide to enhancing your carousel experience

I recently added jcarousel to my website and things are looking good so far. Take a peek at how my site is currently set up: check it out! What I'm aiming for now is a feature where if a user clicks on an image to enlarge, it will open in a new tab ...

Accessing the parent scope from a directive within a nested ng-repeat in AngularJs

Seeking guidance on accessing the parent scope within a directive nested in an ng-repeat. Here is an example: <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="section in sections"> {{section.Name}} <div ng-rep ...

Error: Trying to access a property that does not exist on an undefined object (retrieving 'kind

Currently, I am working on a project using angular-CLI. When I attempted to create a new module yesterday, an error popped up in the terminal saying Cannot read properties of undefined (reading 'kind') (only this error there wasn't an ...

Using React and TypeScript together can lead to issues when trying to use union keys as an index

I've implemented a hook using useState and the delete method to effectively manage my form values. const [values, setValues] = useState<tAllValues>({}); The values stored include: { name: 'Andrew', age: 34, avatar: [{ name: ...

Does v-if cause the jquery clock picker to malfunction?

Here is my unique div where the clockpicker library functions correctly. <div class="input-group clockpicker"> <input type="text" class="form-control" value="18:00"> <span class="input-group-addon"> <span class ...

How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code: html, body { margin: 0px; padding: 0px; } bo ...