Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute.

For example:

[{
   {
     "orderNo":"1",
     "description":"Item 1",
     "note": "Note 1"
   },
   {
     "orderNo":"2",
     "description":"Item 2",
     "note": "Note 2"
   },
   {
     "orderNo":"3",
     "description":"Item 3",
     "note": "Note 3"
   }
}]

And transforming it into:

[{
   '0':[
      {
         'orderNo':'1',
         'items': '[{"description":"Item 1", "note": "Note 1"}]'
      }
   ],
   '1':[
      {
         'orderNo':'2',
         'items': '[{"description":"Item 2", "note": "Note 2"}, {"description":"Item 3", "note": "Note 3"}]'
      }
   ]
}]

With the provided function (from @Barmar), I can accumulate a single attribute into an items array (in this case, itemId).

var newData = [];
for (var i = 0; i < data.length; i++) {
  var orderNo = data[i].orderNo;
  if (!newData[orderNo]) { // Add new object to result
    newData[orderNo] = {
      orderNo: orderNo,
      items: []
    };
  }
  newData[orderNo].items.push('{"itemId":' + data[i].itemId + ',"description:"' + data[i].description); // how than this be converted into a string?
}

How can I concatenate multiple attributes together while preserving their relationship so they can later be parsed with JSON.parse?

Answer №1

One way to achieve this is by utilizing the Array.prototype.forEach method.

x1=[{0:[{time:"2018-02-20",description:"Item 1",note:"Note 1"}],1:[{time:"2018-02-21",description:"Item 2",note:"Note 2"},{time:"2018-02-21",description:"Item 3",note:"Note 3"}]}];
var y1={};

x1.forEach(function(x){  
  var index=0;
  for(var a in x){
    var y={};
    x[a].forEach(function(e){
      y["time"]=e.time;       
      if(!y["items"]){
        y["items"]=[];
      }
      y["items"].push({'description':e["description"],'note':e["note"]});     
    });
    y1[Object.keys(x[a])[index++]]=y; 
  }
});

console.log(y1);

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

How to showcase API JSON data in a dropdown menu in Flutter

Can you assist me in understanding how to piece together these components logically? I have the following elements: 1 - An API that returns JSON data, containing a replicated List<> at the endpoint headsign 2 - A Metadata pop-up populated by a _sh ...

When using PHP's json_encode function with an array of objects, it may result in

In my PHP code, I have an array that looks like this when using var_dump: array(135) { [0]=> object(Book)#138 (2) { ["id"]=> string(36) "93ec4cd6-49a3-4dc6-94f1-00295cc9cdaf" ["title"]=> string(33) "title 1" } [1]=> o ...

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Jquery JSON AJAX Response Timing

I believe the key factor here is timing rather than the code itself. I am seeking advice on the best practice for obtaining a JSON response effectively. <script type="text/javascript"> $(window).load(function() { $(&apos ...

Extracting information from a JSON file using the array name provided in the URL

Currently, I am facing an issue with printing data in JSON format from my 'data.json' file. In my PHP file (alldata.php), I have successfully managed to obtain all the data (arrays) and print them out in a pretty format. However, my challenge lie ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Tips for addressing the error message "Cannot PUT /":

I have been working on updating a local database using MongoDB for my project. Here is the code snippet I am using to update the data. The second part involves editing that redirects the updated data. I am not encountering any errors, so I am unable to i ...

Troubleshooting issue: Dexie.js query using .equals not functioning properly in conjunction with localStorage

I am attempting to retrieve a value from indexedDB using Dexie.js, but it seems that the value stored in localStorage is not being recognized. I have tried various methods including async/await, promises, placing the localStorage call in created, mounted, ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Tips for steering clear of getting caught in the initial focus trap

I have implemented Focus-trap (https://www.npmjs.com/package/focus-trap) in my modal to enhance keyboard accessibility. Here is a snippet of my code: <FocusTrap focusTrapOptions={{onDeactivate: onClose}} > <div> ... </div> <Focu ...

converting rails 3 data into json format for use in javascript

Although to_json is deprecated and as_json is causing issues, I'm facing a problem. The following line functions properly, but to_json is now deprecated: new IS.Presentation(<%= raw(@course_step.step.step_presentation.step_presentation_files.map ...

Some sections of the HTML form are failing to load

I'm currently following a tutorial and applying the concepts to a Rails project I had previously started. Here's my main.js: 'use strict'; angular.module('outpostApp').config(function ($stateProvider) { $stateProvider.sta ...

Generating a fresh array comprised of discovered values within an array (JSON and Groovy)

Here is an array I am working with: R = [ [ Period:[ Price:[x:1, Date:2011, NewPrice:1.000], PriceX:[PriceY:2, Date:2012, NewPrice:1.000] ] ] ] My goal is to extract the values of elements containing Date and create a new array: dates ...

New navigation menu changes as user scrolls

I'm struggling to find a way to implement a different navigation menu that appears when the user scrolls down. I'm envisioning something similar to this example: My goal is to have #small-menu replace #big-menu once the user starts scrolling. C ...