What is the best way to incorporate a random JSON section into a JSON structure?

Let's say I have a JSON message:

json_msg =

[{ LOG: 'TPT',
  TYPE: 'UPDATE',
  UIN: 'VEHICLE',
  SEQ_NO: 20129,
  VALUE: 1,
  TIMESTAMP: 518342.438263017,
  EXPERIMENT: 0,
  IDENT: '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  STAGE: 'START',
  MODE: '' },
{ LOG: 'TPT',
  TYPE: 'UPDATE',
  UIN: 'VEHICLE',
  SEQ_NO: 20129,
  VALUE: 1,
  TIMESTAMP: 518342.438263017,
  EXPERIMENT: 0,
  IDENT: '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  STAGE: 'START',
  MODE: '' }.
{ LOG: 'TPT',
  TYPE: 'UPDATE',
  UIN: 'VEHICLE',
  SEQ_NO: 20129,
  VALUE: 1,
  TIMESTAMP: 518342.438263017,
  EXPERIMENT: 0,
  IDENT: '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  STAGE: 'START',
  MODE: '' }]

and I want to add it to an empty JSON object

var testObject = {}

Now, I need to iterate through the json messages and append them to testObject.

for (let i =0; i< json_msg.length; i++) {
     // TODO 
     testObject.push(json_msg[i])} // doesn't work

Does anyone have a solution for this?

Keep in mind that this is just a test case. In reality, I filter incoming JSON messages and need a method to add these filtered messages into a new JSON Object message (similar to '.push' for arrays).

Answer №1

There are 3 ways to accomplish this task: using Object.assign, {...}, or loops.

let data= [{ "LOG": 'TPT',
  "TYPE": 'UPDATE',
  "UIN": 'VEHICLE',
  "SEQ_NO": 20129,
  "VALUE": 1,
  "TIMESTAMP": 518342.438263017,
  "EXPERIMENT": 0,
  "IDENT": '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  "STAGE": 'START',
  "MODE": '' },{ "LOG": 'TPT',
  "TYPE": 'UPDATE',
  "UIN": 'VEHICLE',
  "SEQ_NO": 20129,
  "VALUE": 1,
  "TIMESTAMP": 518342.438263017,
  "EXPERIMENT": 0,
  "IDENT": '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  "STAGE": 'START',
  "MODE": '' },{ "LOG": 'TPT',
  "TYPE": 'UPDATE',
  "UIN": 'VEHICLE',
  "SEQ_NO": 20129,
  "VALUE": 1,
  "TIMESTAMP": 518342.438263017,
  "EXPERIMENT": 0,
  "IDENT": '.Model.Index_obj.MuLifeCycle_obj.Mu.vh_Transporter:2',
  "STAGE": 'START',
  "MODE": '' }
]
  
  let newObject={...data}
  
  console.log("newObject:",newObject)
  ////or
  let newObject2=Object.assign({},data)
  console.log("newObject2:",newObject2)
  ////or loop
  let newObject3={}
  data.forEach((x,i)=>
  newObject3[i]=x
  )
    console.log("newObject3:",newObject3)

  
  

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

Unveiling concealed data within ajax responses

On every cart change, I am attempting to reset my shipping estimator using ajax. The process works well across the entire page except for the shipping estimate section. Hidden values in use include: <input type="hidden" id="sendto" ...

Error in Android Studio Gradle: Project_info object is not found

Revisiting this question because the answer is no longer applicable, with the link now leading to Firebase: Gradle fails building with "Missing project_info object" I am trying to add the google-services.json file to my Android Studio project. ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

Choosing between classes and styles for styling components in ReactJS

Can you explain why the call to the classes object works in the code below, rather than to the styles object defined as a const at the beginning? For instance, take a look at this demo: className={classes.button} The above line functions correctly. Howe ...

Tips for waiting for a Promise to resolve before returning a new Promise

In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all exis ...

Calculate the time difference between two dates using Moment JS

I have two specific dates that I need to calculate the duration between in a specific format ${y}year ${w}weeks ${d}days In order to achieve this, I have created a function. Here is the code snippet: setTotalDuration(): void { const formattedFrom = ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

Design a button that halts all currently running JavaScript operations on a webpage

Within the parameters set for security reasons on my website, users have the ability to manipulate the JavaScript code on the page. However, there are instances where they may unknowingly trigger a JavaScript process that causes the window to freeze while ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

Tips for populating input fields that are generated dynamically based on the completion of an AJAX request

I am encountering an issue with my HTML code that adds barcode[] and description[] input fields dynamically to a form. The onfocusout event triggers the get_barcode_data JS function, which is supposed to retrieve the barcode description. However, it seems ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Utilizing PHP and JavaScript to showcase images within a div element

Disclaimer: This message pertains to an academic task. I am seeking clarification on the required steps for completion, rather than direct code solutions. My aim is to enhance my understanding of the fundamental components involved. Currently, I am engage ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

Setting up a new package through JPSM installation

I utilize jspm in my web application. My goal is to install the npm:angular2 package without needing to set it up in the config.js file. Instead of loading the angular2 module via jspm, I manually added the angular2 library like this: <script src="jspm ...

Increase the Z-Index of the Header above the Material UI Modal Background

Currently, I'm in the process of developing a mobile version of a web application using Material UI. However, I am encountering some challenges when it comes to matching the designs accurately. My approach involves utilizing the MUI App-Bar in conjunc ...

What is the best way to create a complex JSON array and send it as a parameter in an ajax request?

Facing complexities with a multidimensional array, my PHP code is structured as follows: $result = array(); $count = 0; foreach($matches_lines as $lines){ $match_user = $lines["signup_username"]; $match_birth = $lines["signup_birth"] ...

Using Javascript's document.write function to modify the content of a PHP page

Here is a Javascript function that capitalizes the first letter of a string: function capitalizeFL(string) { return string.charAt(0).toUpperCase() + string.slice(1); } In a file named statuswindow.php, there are PHP scripts that use this function to ...

Differences Between Angular 2 Reactive Forms and Template Forms

We are embarking on a new Angular 2 project and are deliberating on whether to opt for Reactive Forms or Template Forms. If you want to learn more, you can refer to this article: https://angular.io/guide/reactive-forms From what I understand, the main adv ...

Working with JSON responses in ASP.NET

Being a PHP Developer with limited knowledge of asp, I am working on a portal in PHP that requires an ajax post to an asp page on an external server. The response from the asp page is formatted like this: OK|some_id|some_name|some_id|0|1|||some_name|some_ ...