Transforming an array into a JSON object

I currently have an array structured like this:

[ 'quality',
  'print-quality: 4',
  'x-dimension',
  'Value: 21590',
  'Value: y-dimension',
  'Value: 27940',
  'Value: ',
  'Value: media-bottom-margin',
  'Value: 0',
  'Value: media-left-margin',
  'Value: 0',
  'Value: media-right-margin',
  'Value: 0',
  'Value: media-top-margin',
  'Value: 0',
  'Value: ' ]

My objective is to transform this array into a json formatted as follows:

{ "quality": "print-quality: 4",
  "x-dimension": "21590",
  "y-dimension": "27940", 
  "media-bottom-margin": "0",
  "media-left-margin" : "0",
  "media-right-margin": "0",
  "media-top-margin" : "0" 
 }

The task at hand involves eliminating all instances of the string 'Value' and converting it to the specified format above.

Answer №1

In JavaScript, you cannot create an associative array directly as the language does not support it. However, you can achieve a similar result by creating an object.

Here is an example of how to do this:

var data = [ 'quality',
        'print-quality: 4',
        'x-dimension',
        'Value: 21590',
        'y-dimension',
        'Value: 27940',
        'Value: ',
        'Value: media-bottom-margin',
        'Value: 0',
        'Value: media-left-margin',
        'Value: 0',
        'Value: media-right-margin',
        'Value: 0',
        'Value: media-top-margin',
        'Value: 0',
        'Value: ' ],
    cleanData,
    newData = {}; // initializing the new object

cleanData = data
    .map( function(x) { return x.replace(/^Value: /, ''); }) // removes leading "Value: " 
    .filter( function (x) { return !x.match(/^$/); } ); // filters out empty values 

for (i = 0; i < cleanData.length; i += 2) { // iterating over the cleaned-up array
    newData[cleanData[i]] = cleanData[i + 1];
}

The resulting newData object (shown in JSON format for readability) will be:

{
    "quality":"print-quality: 4",
    "x-dimension":"21590",
    "y-dimension":"27940",
    "media-bottom-margin":"0",
    "media-left-margin":"0",
    "media-right-margin":"0",
    "media-top-margin":"0"
}

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

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...

Use Javascript to deactivate the mouse cursor and rely solely on the keyboard cursor for navigation

I am facing an issue with a div that contains a textarea. The cursor is automatically positioned at the beginning of the text within the textarea. I would like to disable the mouse cursor when hovering over the textarea but still be able to navigate within ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

What could be causing me difficulty in integrating NProgress into my Next.js application?

Despite following all the necessary steps for implementing the nprogress package, I am facing an issue where the loading bar shows up when routes are changed but nprogress fails to function properly. I have attempted alternative ways such as linking the st ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

"Encountering a glitch involving Vue.js 3, Pinia, and a centralized store

While using Pinia in a Vue.js 3 project, I encountered an issue. The problem arises when I attempt to load constant JSON structures from my backend using the file src/store/constants.store.ts // @ts-check import { defineStore } from "pinia" impor ...

steps for setting up an endless scroll masonry grid

I have incorporated masonry js to display content on my website. Now, I am interested in adding infinite scrolling functionality using this script. I came across a demo that showcases this feature. However, I am struggling to figure out how to implement ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Is it possible for Vue Router to remember the scroll position on a route and return to the same position when navigating back?

My Vue Router is not saving the scroll position and always loads at the top of the page (0, 0). Any suggestions on what could be causing this issue? Here is my current router code setup: const scrollBehavior = (to, from, savedPosition) => { if (saved ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

Retrieving data from varied React components - triggered by clicking a LOG button

function Copy() { const Message = "MESSAGE"; const [messageList, setMessageList] = useState([{ text: "Hello", id: 1 }]); const [newMessageValue, setNewMessageValue] = useState(0); const addToMessageList = () => { alert(n ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

How can you center popup windows launched from the main window using jquery?

Within my web application, I frequently utilize popup windows that open at different locations on the screen. These popups are standard windows created with window.open() rather than using Jquery. Now, I am seeking a solution to automatically center all p ...

Include new items in the li tag using JavaScript

Hello, I am looking to dynamically add elements to an LI element when a link is clicked. I have successfully added elements to a DIV using the following code snippet: I came across a similar question on Which "href" value should I use for JavaScript links ...

React: The 'Redirect' function is not included in the export list of 'react-router-dom'

When I try to run npm run start in the terminal, an error message appears. 'Redirect' is not exported from 'react-router-dom', causing an import error. I have attempted various solutions like reinstalling node_modules, react-router-d ...

Customizing a tinyMCE button with a unique icon

I'm attempting to insert a Font-Awsome icon into a button that I included in tinyMCE using the following code: ed.addButton('youtube', { title: 'Add Video' , icon: 'icon-youtube', onclick: function () { ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

Sending an array of dictionary objects to a JavaScript function

I have a situation where I need to pass a large amount of data stored in an NSArray containing NSDictionary objects to a JavaScript function using a webview and the method: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script My inquir ...