reconstructing the JSON array

// Here is an initial JSON object to work with
var originalJson = {
  "rows": [{
    "ID": 123,
    "Data": 430910,
    "VersionNum": 0,
    "RowSeqNum": 1,
    "IterationNum": 1,
    "FirstName": "Aqwemara",
    "LastName": "Seweqweebi",
    "Location": "CweAN",
    "Role": "Site",
    "In_Out": "Internal",
    "Editor": "User1",
    "Edit_Date": "2015%2D02%2D25T15%3A30%3A47%2E883Z"
  }]
};


// Array containing keys for the new JSON 
var keyResponse = [];
keyResponse.push("FirstName", "LastName", "Location", "Role", "Editor", "Edit_Date");
var updatedResponse = [];


$(document).ready(function() {
      $('.btn').click(function() {
         
        updatedResponse.push(
            for each(key in keyResponse[{
              key: response[i].key
            }]);

            console.log(JSON.stringify(updatedResponse));
          });
      });
  
    // Additional setup for the console output 
    var consoleLine = "<p class=\"console-line\"></p>";

    console = {
      log: function(text) {
        $("#console-log").append($(consoleLine).html(text));
      }
    };
.console-line {
  font-family: console;
  margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="btn" type="button" id="btn" value="Go!">
<div id="console-log"></div>

I am working on transforming the originalJson, making changes to specific key-value pairs, and reconstructing a JSON based on entries in the keyResponse array.

When rebuilding the object, I aim to include only select keys from the initial JSON structure.

Is it possible to use a loop within the updatedResponse.push statement to achieve the desired outcome smoothly? Any suggestions for improvement?

Thank you!

JSFIDDLE : https://jsfiddle.net/b5m0nk67/5/

Answer №1

If you're searching for a solution, look no further than the map function. It's a handy feature found in modern JavaScript implementations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

By utilizing .map(), your filtering code could take on a structure similar to this:

var wbuResponse = initalJson.map(function(row, index) {
  return {
    FirstName: row.FirstName,
    LastName: row.LastName,
    Location: row.Location,
    Role: row.Role,
    Editor: row.Editor,
    Edit_Date: row.Edit_Date
  };
});

If you prefer the idea of dynamically selecting properties to filter down to instead of hard-coding them, consider this approach:

var props = ["FirstName", "LastName", "Location", "Role", "Editor", "Edit_Date"];

var wbuResponse = initalJson.map(function(row, index) {
  var mappedRow = { };

  for (var i = 0; i < props.length; i++) {
    mappedRow[props[i]] = row[props[i]];
  }

  return mappedRow;
});

To ensure compatibility across various browsers, jQuery offers its own map function with a polyfill for non-supporting browsers. Check out some examples here:

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

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

What is the most effective method for live-updating a field every 5 seconds in Laravel?

I want to monitor the database to see if a new row is created for each user and display a popup message to notify them. I'm debating between using pusher/socket or making an Ajax call every 5 seconds to achieve this live update without page refresh. I ...

What steps should I take to fix the TypeScript Compiler issue "Global member 'NodeJS' has no exported namespace 'Global'?"

QUERY: What steps should I take to fix the Typescript Compiler (tsc) error stating "Namespace 'NodeJS' has no exported member 'Global'"? Upon executing tsc, this particular error unexpectedly appeared in a project that is considered "l ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

Locating a specific element within an array using AngularJS / Conditional statement within ng-class

I am working on a feature where I need to identify the current user in a list of all users. Below is an example of what my code currently looks like. <div class='user' ng-repeat='user in users'> <span class='name'& ...

Leveraging the power of MySQL and PHP to handle nested JSON data in AngularJs with ng-options

Can someone please guide me on how to generate nested JSON data using MySQL and PHP in Codeigniter? I am looking to structure my data in the specific format shown below. $data = { 'India': { 'Andhra Pradesh': ['Vijay ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Transforming a JSON array into FormData results in a string representation

When I convert JSON data into Form data in my React app and send it to the server, the arrays and objects are being converted into strings on the server end. var formdata = new FormData(); for (let i = 0; i < images.length; i++) { formdata.append( ...

Navigate to a specific element using Selenium WebDriver in Java

Currently, I am utilizing Selenium along with Java and ChromeDriver to execute a few scripts on a website. My goal is to scroll the driver or the page to a specific element positioned on the webpage. It is important that this element is visible. I am awa ...

Utilizing AngularJS's ng-repeat directive to iterate over an array stored in a $

My controller successfully retrieves and pushes an object onto an array using Parse: var mySite = angular.module('mySite', []); mySite.controller('listConnectors', ['$scope', function ($scope) { //Parse.initializ ...

Choosing between global and local Node packages can be a crucial decision that affects

Recently, I discovered that Angular 2 is installed globally on my system, but I can't remember when I did that or if it's the recommended setup. It seems redundant since Angular can be defined in each project individually. This situation has me ...

Bytecode representation of arrays and records

In C, I am in the process of developing a brand new programming language and would like to refrain from using third-party code for variable handling. My main concern is how to efficiently represent array assignments, such as apples_in_crate[5] = 170, in b ...

Exploring SQL Components with JavaScript

Here is the code I am currently using: //This function handles all games and their attributes function handleGames(){ sql.query('SELECT id FROM games', function (err, rows){ if(err){ console.log(String(err).error.bgWhite) ...

React - verifying properties

Here's a question that I've been pondering. In many situations, we find ourselves needing to check if props are undefined. But what about nested props? For example, let's say we have: this.props.data.income.data1.value.chartData and we wa ...

Chrome's Ctrl-Shift-N event binding

I have implemented jQuery.hotkeys to handle keyboard events. Currently, I am attempting to bind the combination of Ctrl+Shift+N $(document).bind('keydown', 'ctrl+shift+n', function(e) { e.preventDefault(); alert('Ctrl+Shi ...

Is it possible for browsers to handle PUT requests using multipart/form data?

Is it common for HTML forms to not support HTTP PUT requests when submitted from certain browsers like Google Chrome? <form id="#main-form" action="http://localhost:8080/resource/1" method="put" enctype=" ...

Tips for showcasing information from an array in an object using Angular 2 or newer versions

My Information consists of 2 offices while another contains just one office "id": "1", "username": "sample", "groups": "Admin", "office": [ { "officeid": "2", "officename": "sky" }, { "officeid": "3", "off ...