Build an intricate nested array structure using the properties of an object

My data object is structured like this:

"parameters": {
    "firstName": "Alexa",
    "lastName": "Simpson",
    "city": "London"
  }

The task at hand involves implementing the following request: https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate

I aim to construct an array of objects where the key of my data object corresponds to the value of "text". For example, "firstName" should map to {{text1}} and "Alexa" should map to "replaceText1" dynamically.

{
  "requests": [
    {
      "replaceAllText": {
        "containsText": {
          "text": "{{text1}}",
          "matchCase": "true"
        },
        "replaceText": "replaceText1"
      }
    },
    {
      "replaceAllText": {
        "containsText": {
          "text": "{{value2}}",
          "matchCase": "true"
        },
        "replaceText": "replaceText2"
      }
    }
    
  ]
}

Answer №1

To transform the key/value pairs of obj.param into request objects, you can utilize the Object.entries method along with the map function. Each pair is used to create an object with a key of requests:

const obj = {
  "params": {
    "name": "Alexa",
    "lastName": "Simpson",
    "city": "London"
  }
}

const req = {
  "requests": Object.entries(obj.params).map(([text, value]) =>
    ({
      "replaceAllText": {
        "containsText": {
          "text": text,
          "matchCase": "true"
        },
        "replaceText": value
      }
    }))
}

console.log(req)

Answer №2

Give this a shot. This code snippet utilizes the Object.entries method to extract the key-value pairs from an object and create new objects based on them. You can then parse the `params` object using JSON.parse.

params = {
"name": "Alice",
"lastName": "Smith",
"city": "Paris"
}

requests = []

for (const [key, value] of Object.entries(params)) {
  requests.push({
    "replaceAllText": {
      "containsText": {
        "text": key,
        "matchCase": "true"
      }
    },
    "replaceText": value
  })
}

console.log(`{requests: ${JSON.stringify(requests)}`)

Utilize JSON.stringify to convert the resulting output into a string.

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

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

The tweet button is not displaying correctly on the website

Visit my website here, where I have integrated a tweet button generated from Twitter.com. It was working fine for the initial few posts, but now it is failing to load and only displaying text. I have checked the console for any JavaScript errors, but so f ...

Flask's JSON data format

When it comes to fetching data from a URL generated with Flask and not by me using AngularJS and Restangular, I seem to be encountering some issues. The JSON data I have is as follows: {"patients": ["{\"_id\": {\"$oid\": \"5677d63 ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

There is an issue with decoding JSON in the Flask API response using Python

I created a basic Python API with flask, and this is what my response looks like... response = { "id" : "345345d", "topdata" : { "top" : 234, "left" : 42, }, "bottomdata" : { "color" : "red", "bg" : "bl ...

What is the best way to retrieve the name of a Meteor package from within the

As I work on developing a package, I am looking for ways to dynamically utilize the package's name within the code. This is particularly important for logging purposes in my /log.js file. My main query is regarding how I can access the variable that ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

What is the best way to access nested JSON data in Vue.js code demonstrated here?

How can I properly access the nested JSON data for stage.name provided in the example below? As shown in the template, my attempt to retrieve the stage name is not working. Using vue.js created() { url="http://{{ api_endpoint }}" fetch(url) ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

Error encountered while trying to serialize the JSON array

As someone who is relatively new to working with API's, I've encountered an issue where I'm getting a "graphconnection is not serializable" error when attempting to json.dumps an api response. Despite the response appearing to be in json arr ...

Retrieving an AJAX array POST in Laravel 5 Controller

Below is the structure of my form: <td> <input type="text" name='name[]' class="form-control"/> </td> <td> <input type="text" name='mail[]' class="form-control"/> </td> <td> <select na ...

Shopping cart feature in PHP - Ajax response only functioning once

I'm in the process of developing a shopping cart. I start by adding products to the cart, then use Ajax to dynamically update the quantity when it changes. Everything works smoothly after the first change, but subsequent quantity updates do not refres ...

importing information into MySQL database from website address

Two URLs are at my disposal: Navigate to URL 1 Go to URL 2 I am eager to import these URLs into a MySQL database using PHP code and update them every 10 minutes. Despite my efforts with the following code, it seems to not be working as expected: <? ...

Lately, I've been coming across mentions of "myApp.controllers" and "myApp.modules" in Angular JS. Can anyone explain the significance of these terms?

Recently, I've come across code that looks like this: angular.module('app.controllers') This pattern has appeared in a few tutorials I've read. However, the purpose of the .controllers within the module name is unclear to me. I'v ...

Utilizing Font Awesome icons within a JSON structure

I'm running into a bit of trouble trying to display font awesome icons. The text is written in json using a rakefile, and I'm attempting to insert a font awesome icon within the text. However, I'm facing difficulties because the text is in j ...

Having trouble debugging a website remotely? Dealing with a JSON problem specifically in IE8

Currently, the website is functioning flawlessly on various machines except for those used by the client in Africa. Unfortunately, I have no way of accessing his specific machine due to geographical constraints. The client has limited IT knowledge, and we ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

Troubleshooting: Issues with Ajax loading page and click functionality in jQuery

Why won't my ajax function properly? Here are the details of my pages. I am using JQuery to monitor click events and implement ajax for loading the responder page. Can you spot any issues in this code snippet? index.php <html> <head ...