Incorporate Nested JSON within JSON using JavaScript

I am currently dealing with a table that has been created using ng-repeat for rows and columns.

ng-model="tableValues[row][column]"

The values for row and column are obtained from ng-repeat. The data in the table consists of dropdowns, which I want to populate from a list of values.

However, when I try to write values to the ng-model from the controller, it ends up overwriting existing values for columns.

var x ={};
for(objData){
        row = objData[i]["row"];
        column = objData[i]["column"];
        value = objData[i]["value"];
        x[row]={};
        x[row][column]=value;
        vm.tableValues=x;
}

//objData is an array of objects where each object contains the value along with its corresponding row and column.

Although this code creates the correct JSON structure, it keeps overwriting values for columns.

{"r1":{"c1":"v1"},"r2":{"c2":"v2"},"r3":{"c2":"v2"}}

what I actually need is:

{"r1":{"c1":"v1","c2":"v2","c3":v3,"c4":"v4"},
{"r2":{"c1":"v1","c2":"v2","c3":v3,"c4":"v4"}.......} 
and so on..

Instead of replacing previous column values when putting them inside a row JSON by comma, I want all column values to be retained.

Answer №1

To optimize your code, you can apply the reduce function to both the rows and columns:

var rows = ['r1', 'r2', 'r3', 'r4', 'r5'];
var columns = ['c1', 'c2', 'c3'];
var values = ['v1', 'v2', 'v3'];

let result = rows.reduce((previous, currentRow) => {
  previous[currentRow] = columns.reduce((accumulator, currentColumn, index) => {
    accumulator[currentColumn] = values[index] || "no value";
    return accumulator;
  }, {});
  return previous;
}, {});

console.log(result);

Answer №2

Give this a shot:

let myObj ={};
    let rows=["r1","r2","r3","r4","r5"]
        let columns=["c1","c2","c3"]
        let values = ["v1","v2","v3"]
        
    for(let i=0;i<rows.length;i++){
      for(let j=0;j<columns.length;j++){
        if(!myObj[rows[i]])
           myObj[rows[i]]={};
        myObj[rows[i]][columns[j]]=values[j] || "no data";
      } 
    }
    console.log(myObj);

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

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

Node.js Objects and String Manipulation

Within my nodeJS scenario, I am working with an object that includes both elements and an array of items: var Obj = { count: 3, items: [{ "organizationCode": "FP1", "organizationName": "FTE Process Org" }, { "organizationCode ...

Managing and retrieving data in bulk from an indexed database as JSON format

I am currently developing an application that utilizes IndexexDB for local data storage. I am looking for a way to extract and insert large amounts of data from an indexed DB in JSON format. Below is the code snippet illustrating what I have accomplished s ...

Unable to utilize Bootstrap inside the Shadow DOM of Custom Elements

I am currently in the process of developing a web component using plain JavaScript and implementing Bootstrap 5 for styling purposes. While the Bootstrap styling is functioning correctly, I am encountering issues with the event listeners for the Bootstrap ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

The modal window displays an error upon submission and prevents itself from closing

Below is the HTML code for a modal form: <form action="" class="cd-form" method="POST" id="signinform" onsubmit="return: false;"> <p class="fieldset" id="warningPanel"> <?php ShowAlertWarning(); ?> </p> <p ...

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

Is there a way to change the color of a specific tab without affecting the content within it

I am attempting to change the color of an individual tab using jQuery. However, when I set the background attribute in CSS, it colors the entire background instead. What specific property should I be setting to only change the color of the tab itself? ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

How to showcase an item in Angular 2

Alright, I have the following data: { "calledCust": { "no": 270, "yes": 9 }, "hasOpened": { "no": 254, "yes": 25 } } I've been attempting to display this in the view using the code below. <ul *ngFor="let profile of profiles.counts"> <li& ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

The Angular bootstrap datepicker does not correctly format the date value stored in the ng-model variable

I am currently utilizing a bootstrap date-picker in my Angular application. However, whenever I select a date from the date-picker, the underlying ng-model that I have bound gets updated. I would like that ng-model to be in the date format 'MM/dd/yyyy ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

WebApi Failing to Properly Deserialize Data

I'm at my wit's end here. I think I just need another set of eyes. Method Signature: public async Task<IHttpActionResult> Post(ApiRequest request) Model: [SuppressMessage("ReSharper", "CollectionNeverUpdated.Global")] [SuppressMessage(" ...

What are the different ways to interact with the object retrieved from the onloadedmetadata event

Having trouble accessing a specific value in an object that is the result of the onloadedmetadata event. When I log the entire object using audioDuration, I am able to see and retrieve the respective value without any issues. However, when I try to access ...

Universal Navigation Search Component for Vue Router

Just starting out with Vue and frontend development. I'm attempting to create a universal navigation bar in Vue Router using bootstrap vue, complete with a search bar feature. However, because I have placed my navigation bar in App.vue, I am encount ...

Unraveling the mystery: accessing the same variable name within a function in JavaScript

What is the best way to reference the same variable name inside a function in JavaScript? var example = "Hello"; console.log("outside function: " + example) function modifyVariable() { var example = "World!"; console.log("inside function: " + ex ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

Indistinct. Applies to every case class with a single constructor parameter

Currently, my goal is to develop Json serializers for all case classes with a single argument constructor using shapeless in a generalized manner. Here's what I have accomplished so far: object ShapelessJsonOFormat extends ProductTypeClassCompanion[ ...

Retrieving a variable from a JSON array with multiple dimensions using jQuery

Currently, I am working on fetching a multidimensional JSON array using JQUERY. I am facing challenges in extracting specific items from the array and inserting them into the HTML. I need assistance in navigating through the array to retrieve these elemen ...