Is there a way for me to enclose the json value within curly braces?

Imagine a scenario where I have JSON data structured like this (using JSON.stringify)

{ name: 'Bill', lastname: 'Smith'}

Now, I wish to transform the values by wrapping them with curly braces as shown below

{ name: { value: 'Bill' }, lastname: { value: 'Smith'} }

Does anyone have an approach in mind to accomplish this using JavaScript or lodash?

Answer №1

To transform the input object, one approach is to use `Object.entries` followed by mapping to a nested object and then using `Object.fromEntries` to convert it back:

const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.fromEntries(
  Object.entries(input).map(
    ([key, value]) => ([key, { value }])
  )
);
console.log(newObj);

If you are targeting older browsers that do not support `Object.fromEntries`, you can consider using a polyfill or alternative methods like `.reduce`:

const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.entries(input).reduce(
  (a, [key, value]) => {
    a[key] = { value };
    return a;
  },
  {}
);
console.log(newObj);

Answer №2

To iterate through the keys of an object, you can utilize for...in loop and update it as shown below:

const input = { name: 'Bill', lastname: 'Smith'};

for (const key in input) {
  input[key] = { value: input[key] }
}

console.log(input)

If you prefer creating a new object instead of modifying the input object, you can do so by following this approach:

const input = { name: 'Bill', lastname: 'Smith'},
      output = {}

for (const key in input) {
  output[key] = { value: input[key] }
}

console.log(output)

Answer №3

One way to create a new object with transformed values is by using the _.mapValues() method from lodash library:

const obj = { animal: 'cat', color: 'black'};

const updatedObj = _.mapValues(obj, val => ({ val }));

console.log(updatedObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

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

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...

What is the process for implementing a third-party component in my web application?

After some experimentation, I've discovered that it's necessary to include the link to the css files in the header and then mention the link to the js files before the closing tag. However, I encountered difficulties when trying to use a compone ...

What is the correct way to chain Promises for the tasks of creating a new user and hashing their password simultaneously?

My goal is to send a POST request to create a new account. The process involves checking if an account with the same email exists. If not, a new account is created and stored in a user collection. Additionally, password hashing and token generation are per ...

Encountering issues when using array.map with null entries in a react application

Struggling to iterate over the location array and map it? Despite several attempts, handling the null object within the array seems challenging. What am I missing here? While using a for loop resolves the issue, the map function is proving to be a roadbloc ...

Insert the text into a table data cell once the drop-down selection has been changed

I am attempting to display my ajax results in the td element next to my dropdown menu that triggers the ajax call when changed. Each row contains a similar id where I intend for the text to be shown (I'm sure there is a simpler solution). Below is my ...

Issue encountered when attempting to synchronize Protractor with the page: "unable to locate Angular on the window" while executing a Protractor test case

Currently, I am conducting tests on an Angular website. Our application flow begins with a Login page followed by a vertical application selection frame (located in the left corner of the page) that consists of non-Angular web pages. Once the user selects ...

Passing a specific input value from an array of inputs in JavaScript

I'm currently using a query to populate a list of messages by running a loop. Here's the code snippet: <?php $sql_i_msg_sent_waiting="SELECT t1.i_message_id,t2.username,t2.name,t2.propic,t2.age,t2.dob,t3.religion,t3.caste FROM candidate_i_me ...

Is it possible to utilize md-select from Angular Materials to execute a function?

Encountering a peculiar issue with the md-select element - I may be using it incorrectly. The goal is to redirect to a new page or sign out based on the selected option, but instead, I'm faced with this error: Error: Failed to execute 'removeChi ...

Guide on transforming simple values into a JSON format with a schema that adjusts dynamically

I have a list of data values stored in a CSV file, along with a JSON schema that has the ability to change during runtime. My goal is to generate a JSON output based on the schema and populate it with the corresponding values from the CSV. For example, le ...

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

Adding the text-success class to a Bootstrap 5 table row with zebra striping does not produce any noticeable change

I am encountering an issue with a Bootstrap 5 table that has the class table-striped. When a user clicks on a row, I have implemented some jQuery code to toggle the class text-success on the row for highlighting/unhighlighting purposes. The highlighting f ...

The 'unsubscribe' property is not found on the 'Observable<DataSnapshot>' type

I am facing a typescript error in my code, specifically in the tslint plugin of Atom editor. Unfortunately, I am struggling to determine how to correctly set the type. Error message: https://i.sstatic.net/VU3ee.png Here is the code snippet for the chat c ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Submitting forms through Vanilla JavaScript using AJAX

Can anyone assist me in implementing an AJAX form submission using Vanilla JavaScript instead of jQuery? I have the following jQuery code that needs to be converted: document.addEventListener('DOMContentLoaded', function() { document.querySelec ...

Is there a way to restrict the number of line breaks in a multiline asp:TextBox control?

Is it possible to restrict a multiline asp:TextBox to only display content on 3 lines using either javascript or C#? ...

Unidentified Angular JS HTML Functions

Currently, I am developing an application that retrieves data and presents it in a tabular format. To implement sorting and pagination features, Angular JS is being utilized. The pagination section of the app is dynamically added through an Angular functio ...

pressing buttons on user interfaces nested two levels deep

There is a 3rd party library (which cannot be altered) with the following interface: interface MyInterface { x: { a: 1, b: 2, c: 3, }, y: { d: 4, e: 5, f: 6, }, z: { g: 7, ...

Using JQuery to Retrieve JSON Data from an HTTPS Endpoint

I am attempting to retrieve a JSON file from an https secured website without using server-side languages. The client specifically requested that the process be entirely implemented in JavaScript. After some research, I discovered that I need to utilize J ...

Create a PDF document with the background of the input text included and printable

I am trying to find a way to make the background image of the input text appear when saving the page as a PDF (right-click, select "Print ...," and then "Save as PDF"). The page has a square background image that creates the effect of each character being ...