Create a collection of data by retrieving values from a web service response

My goal is to populate table values from a webservice response. The issue arises when the response format is not compatible with the table. The response structure may vary.

0:{name: "image.png", base64: "iVBORw"}
1:{name: "download.png", base64: "iVBO"}
2:{name: "test-animation.gif", base64: "R0lGODlhLAEs"}

How can I transform it to the desired format?

[["image.png", "iVBORw"],["download.png", "iVBO"],["test-animation.gif", "R0lGODlhLAEs"]]

This is my approach:

$.cordys.ajax({
method: "somewebservice",
namespace: "Package",
parameters: {
emailid:mailidvalue
},
dataType: '* json',
 success: function (result) { 
 output=result;
 bodycontent=output["data"]["body"];
 var attachvalue=result.data.tuple;

 $('#attachmenttable').DataTable( {
        "data": attachvalue,
        columns: [
            { title: "File Name" },
            { title: "Base64" }
        ]
    } );
                       },
error: function(err){
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Answer №1

There is a direct correlation between the given data and the desired outcome. To achieve this, you can utilize either Array.prototype.map() or $.map.

var given = {
  0: {
    name: "image.png",
    base64: "iVBORw"
  },
  1: {
    name: "download.png",
    base64: "iVBO"
  },
  2: {
    name: "test-animation.gif",
    base64: "R0lGODlhLAEs"
  }
};

var desired = Object.keys(given).map(function(key) {
  return [ given[key].name, given[key].base64 ];
});

console.log(desired);

var given = {
  0: {
    name: "image.png",
    base64: "iVBORw"
  },
  1: {
    name: "download.png",
    base64: "iVBO"
  },
  2: {
    name: "test-animation.gif",
    base64: "R0lGODlhLAEs"
  }
};

var desired = $.map(given, function (value, key) {
  return [[ given[key].name, given[key].base64 ]];
});

console.log(desired);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Add the teams-js library to your Vue.js project

I'm currently working on integrating the Microsoft Teams SDK into my Vue.js project. After installing the npm package and referencing it in my vue-file, I noticed that the microsoftTeams alias is displaying as undefined. Is there a step I may have ove ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

A simple guide to positioning an image between two lines of text with Material UI

I am trying to design a banner area with an icon on the left and two lines of text (title and sub-title) in the middle. However, when I implement this structure, each element appears on a separate line. You can view the issue here: https://codesandbox.io/ ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

JavaScript code that is condensed for efficiency without sacrificing readability and maintainability

As a novice in the world of javascript, I find that studying pre-existing code helps me learn a great deal. I've encountered some extensive javascript projects with minified code that becomes almost indecipherable when expanded. Most variables and f ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

Use Node and Express with JavaScript to store HTML form data in JSON format within a .json file

Just starting out with node and express. I am capturing user input from an HTML form and attempting to append or push it in a .json file. I tried using the jsonfile npm package but the data is not being stored in an array format in the JSON file. Here is ...

Transferring information between container and component with Meteor React

I'm facing a challenge with passing data from a container to a component in the context of Meteor and React. Despite following the steps in the Meteor React tutorial and making some customizations, the code doesn't seem to be working as expected. ...

How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign width to these elements? ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

Alter data in MongoDB based on specific circumstances

Currently, I am utilizing node.js and mongoose for a project. The task at hand involves updating database information only if the required field either does not exist in the database or its value is less than 'x'. Specifically, this pertains to ...

Insert metadata tag into the head element of the parent iframe

I am looking to insert a meta tag element into the head element of an Iframe parent. I attempted window.parent.$('head').append('sometext'); This method worked when the source file and iframe file were in the same folder, however it d ...

Can Ember store in Route handle Post requests?

Is there a way to use ember store functionality similar to this.store.findAll('report') for making POST requests with postObj in my route? Also, how should I handle the response received from these requests? Right now, I am sending ajax POST requ ...

"Unlock the power of Passport.js: A guide to leveraging async rendering for email templates

Currently, my setup involves running Express with Sequelize/MariaDB and Passport.js to handle user authentication. Everything seems to be working smoothly except for the activation email that needs to be sent out after a user signs up. Despite having the ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Typeahead AJAX in Bootstrap 3

I have implemented the Bootstrap 3 Typeahead plugin This is my current code: <input type="text" class="typeahead" autocomplete="off"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script&g ...

Securing attributes in Rails 4 models: Best practices and strategies

Suppose I have a model called User, which contains certain attributes that need to be visible within the app. However, when sending this data to a client (where the Rails app acts as an API), some properties of the User should automatically be hidden in th ...

What is the best way to add data-content to hr:after using JavaScript?

Adding style to an element in javascript can be simple. For example: myElement.style.color = "red"; However, what if I wanted to achieve something like this: hr:after { content: "myRuntimeValue" } Is there a way to do this using javascript? ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...