Include a separate key for every element within a JSON array using JavaScript

Looking for assistance to convert the JSon structure below. The size of the input JSon array may vary. I'm struggling to identify the repetitive pattern.

 var input = [{
    "value": 1
 }, {
    "value": 2
 }]

 var output = [{
    "key": {
        "value": 1
    }
 }, {
    "key": {
        "value": 2
    }
 }]

Your help is much appreciated!

Answer №1

To start, initialize a new array and utilize the Array#forEach method to add an object with a key = key pair along with the current item being iterated from the input.

var input = [{value:1},{value:2}],
    result = [];
    input.forEach(item => result.push({ 'key': item }));
    
    console.log(result);

Answer №2

If you give this a try, it might just be the solution you're looking for!

result = array.map(item => ({ "name": item }) );
console.log(result);

I opted for ES6 to keep things straightforward, but the functionality remains intact.

Answer №3

In my opinion, this method is the most traditional and hands-on approach to solve this problem.

const data = [{
    "value": 1
 }, {
    "value": 2
 }],
 result = [],
 newItem,
 index = 0, length = data.length;
 
 
 for(index; index < length; index++){
  newItem = {};
  newItem.key = {"value":data[index].value};
  result.push(newItem);
 }
 
 console.log(result)

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 detect when an option is selected in a Material UI autocomplete component?

Utilizing the autocomplete feature with filterOptions to propose adding a new value: <Autocomplete multiple name="participant-tags" options={people} getOptionLabel={(option) => option.name} renderInput={(param ...

What is the best way to display a placeholder instead of the state's value when a page loads?

I'm having trouble displaying the placeholder of an input instead of its state value. When the page loads, it shows an empty select box because the testType state is null initially. How can I make sure that only the placeholder is shown instead of the ...

Scaling up the window size in Scalatest PlusPlay Selenium is causing resizing issues

After spending a good amount of time on this, I am struggling to figure out how to resize a window using scalatest plus. I have searched online and looked through the documentation at The method I found is executeScript("window.resizeTo(700, 700);") ...

Data recording error: JSON input ended unexpectedly due to syntax error

My database can record data successfully, but when using ajax loading, the success method is not being triggered. What could be causing this issue? Error: "SyntaxError: Unexpected end of JSON input at Object.parse (native) at n.parseJSON " record ...

Tips for utilizing the tencoding's getstring function with a subsection of a fixed array without the need for block copying

I am facing a challenge with applying Tencoding.UTF8.Getstring to a specific part of a static bytes array without having to copy its content to a dynamic array. When dealing with a dynamic array, I can easily use the following syntax: stringvar:=Tencoding ...

The JSON response is not displaying in the correct order as dictated by the SQL query

Having an issue with the JSON array sorting. Initially, the order is not as expected (based on SQL query). The main problem arises when the page loads and the SQL query is called with lastPoll=null - the results are not sorted by time1 DESC, instead they ...

jQuery: Revealing or concealing several divs upon selection alteration

When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN. Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hi ...

How can I transfer data from a C# code to a JavaScript file in asp.net?

I am faced with the task of transferring values from a C# class to a JavaScript file. To achieve this, I have generated a string in C# which contains the values of the list as follows: count = 0; JString = "["; for(i=0; i<x; i++) { JString += "{Sou ...

How to parse JSON data in ASP.NET MVC without a root object and containing a single array

I'm currently in the process of developing a web application that relies on a third-party API to retrieve JSON data. The specific JSON data I am receiving is as follows: { "CompanyID": 14585, "CompanyName": "The Morgan Group ...

Efficiently managing AJAX requests in PHP

One aspect of my work involves a substantial amount of UI coding that requires sending AJAX requests to the backend PHP. I've been managing this by using: if(isset($_REQUEST["UniquePostName"])){ /* Do Something*/ } if(isset($_REQUEST["AnotherUniqueP ...

Storing session data for each HTTP request in a "global" variable using NodeJS

Linking back to a thread that is two years old where the topic aligns closely with what I am looking for. In the realm of C# development, there exists a Session object that holds user session information and can be accessed from any location. This object ...

Showing information on a grid view in Asp.net

I am encountering an issue with two sets of datasets. The first dataset contains 20 records while the second dataset contains 21 records. Strangely, when I attempt to display the records from the second dataset on a grid view, none of them show up. However ...

Explanation of coding line

I recently started diving into a book on buffer overflows and shellcode, and came across the following code snippet. Most of it makes sense to me, but I'm puzzled by the purpose of buffer = command + strlen(command);. If I use memset() on the buffer ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Sending information from a directive to a controller

I'm working on passing a resource from a directive scope to a controller scope by utilizing a callback provided in the view. However, I'm encountering an issue where the argument variable is showing as undefined. Can you help me figure out what I ...

Volley JSON Exception: Unexpected end of data at position 0

I have encountered a problem while trying to utilize Volley for REST calls. Specifically, when attempting to make a Put call with a JSON Object as a parameter, I am receiving an error message stating: error with: org.json.JSONException: End of input at cha ...

How to selectively import specific modules in three.js using ES6 syntax

I recently integrated the three.js library using NPM with the goal of leveraging its new ES6 modular architecture. This design allows for selective importation of specific modules as outlined in this resource: Threejs - Import via modules. For bundling an ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Tips for retrieving multiple groupings in Laravel's blade template system

Hello, I am facing an issue with fetching an array grouped by date and id in Laravel Blade. I have a result like this https://i.sstatic.net/Wo3mT.png. I have tried using a foreach loop, but it is not giving me the desired result. Here is the code I have ...