Adding pairs of keys and values to an array

I am working with a dictionary-like variable in JavaScript, named "dict".

var dict = {
  val1 : ["a", "b", "c"],
  val2 : ["d", "e", "f"],
  val3 : ["g", "h", "i"],
  ...
}

My goal is to extract val1, val2, val3 and store them in an array to display as JSON.

{
  "Configs" : [
      "val1" : ["a", "b", "c"],
      "val2" : ["d", "e", "f"],
      "val3" : ["g", "h", "i"],
   ]
}

I am wondering if it's feasible to push these key-value pairs into an array. And how can I access these values? arr[1].key()?

arr = 
[
   {val1 : ["a", "b", "c"]},
   {val2 : ["d", "e", "f"]},
   {val3 : ["g", "h", "i"]},
]

Answer №1

It seems like what you are looking for is something along these lines:

    var list = {
      value1: ["x", "y", "z"],
      value2: ["1", "2", "3"],
      value3: ["4", "5", "6"],
    }

    var object = {
      Items: []
    };

    for (var key in list) {
      if (list.hasOwnProperty(key)) {
        var item = {};
        item[key] = list[key];
        object.Items.push(item);
      }
    }

    alert(JSON.stringify(object));

This code snippet will generate an object structured like this:

{
  "Items" : [
      { "value1" : ["x", "y", "z"] },
      { "value2" : ["1", "2", "3"] },
      { "value3" : ["4", "5", "6"] },
   ]
}

If you need to access a specific value based on a key (e.g. value2), you would have to search the array for that particular key. If you require that level of accessibility, it might be worth reconsidering why you converted it from a dictionary format originally.

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

What is the best way to interact with parent elements inside an iframe?

I'm working on a fresh image uploader where I aim to place the file input in an iframe and display the uploaded images on the parent page. How can I achieve access to the parent elements from within the iframe? Any examples would be greatly appreciate ...

The requested file at http://localhost:7575/index.js could not be found and was aborted with a 404 error

https://i.sstatic.net/ww9AU.png I have set up endpoints for HTML pages, but I am facing an issue where images and files are not being pulled. Every file path I try results in the error message "GET http://localhost:7575/index.js net::ERR_ABORTED 404 (Not F ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Creating code in AngularJS

I have the following template structure: <h1 class="text-center" ng-bind-html="row.text"></h1> When the content of my row.text is a string like this: Hi your name is {{ name }} It will display as shown below: Hi your name is {{ name }} ...

Verifying the authenticity of a Stripe discount code

My goal is to allow users to apply a coupon code on my website, triggering a check in the Stripe dashboard. Currently, I have implemented the following code snippet, but I am facing an issue with transferring the validCoupon data from the client side to th ...

Trouble encountered while integrating Cloudinary with ExpressJS

I am facing an issue while working on my expressjs code with cloudinary. When I try to set the path for uploading an image, it throws an error saying that the path is not defined. I'm having trouble figuring out what went wrong. This is how I have im ...

Discrepancies in collision box alignment causing ThreeJS SAT collisions to fail

Currently, I am working on developing a simple game project for my school. However, I have encountered an issue with the collisions in the game. The collision boxes appear to be misaligned. If you wish to see the game I am working on, you can access it he ...

Material-UI Issue: Why is makeStyles not working as expected?

Encountered Error: TypeError: Object(...) is not a function 13 | import { connect } from 'react-redux'; 14 | 15 | > 16 | const useStyles = makeStyles(theme => ({ 17 | ...theme 18 | })); 19 | Code Snippet: const useStyles ...

transferring a 2D array from C# to unmanaged C++ through a C++/CLI wrapper

I am currently working on a project that requires optimization, and I need to convert a portion of code from C# to C++. I have started using a C++\CLI wrapper, but I am still grappling with this new approach and haven't fully grasped it yet. Unfo ...

Use dots to bridge the gap between two text elements

Trying to find a way to automatically adjust spacing between two objects has been a challenge for me. Specifically, I am dealing with menu items and their corresponding prices. The desired outcome would look something like this: Burger................. ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

The Next JS Middlewares are experiencing issues with malformed URLs. It is recommended to only use absolute URLs to

I've encountered an issue with the code in my _middleware file that is located within the pages folder. Every time a request is made, it keeps throwing a URL malformed error. Here's the code snippet: const token = await getToken({req, secret: pr ...

callback that returns a local variable

I'm struggling with creating a method that should return an array, but for some reason, the returned value is empty. I suspect it's because the return statement is executed before the local variable is properly set. Perhaps I am approaching this ...

Passing refs from child components to parent components in React v16 using a wrapper component

I have a current component hierarchy that is structured like this: const Parent = props => { const divElement = useRef() // handle divElement logic return <Child ref={divElement} {...some props} /> } const Child = React.forwardRef((props, r ...

Element in Vue.js not recognized

Recently, I decided to dive into Vue.js as a beginner and started working on an app to manage my daily tasks. However, I encountered Vue Components along the way and ran into an error that has me puzzled: vue.js:1023 [Vue warn]: Unknown custom element: ...

Decoding with Decodable for dictionaries containing arrays of strings

Can someone help me with parsing the JSON file below? I keep encountering the error: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil ...

Determine if a string is a palindrome using struct data type in C++

Looking for a way to determine if a word is a palindrome using struct data type or object. The goal is to read data from a file, check if the word is a palindrome, and then reverse the order of the words (already achieved). Below is the code snippet: #inc ...