Adding static JSON array data to the results received from an API call

Within my code snippet below, I am able to retrieve a JSON Response:

respArray = []
      respArray = respBody.classifiers
      respBody = respArray
      if (respBody.length > 0) {
        respBody = applyPagination(respBody, reqParams.filter, options)
      }

The JSON response looks like this:

[
{
    "classifier_id": "improper",
    "name": "improper",
    "owner": "",
    "status": "failed",
    "core_ml_enabled": true,
    "explanation": "",
    "created": "2019-07-04T14:28:37.402Z",
    "classes": [
        {
            "class": "impropertest"
        }
    ],
    "updated": "2019-07-04T14:28:37.402Z"
},
{
    "classifier_id": "improper",
    "name": "improper",
    "owner": "",
    "status": "failed",
    "core_ml_enabled": true,
    "explanation": "",
    "created": "2019-07-05T08:31:55.463Z",
    "classes": [
        {
            "class": "impropertest"
        }
    ],
    "updated": "2019-07-05T08:31:55.463Z"
}]

In addition to this dynamic JSON response, I have a predefined static JSON that I intend to append:

Sample Static JSON:

 "defaultClassifiers":{
"classifiers": [
  {
    "classifier_id": "general",
    "name": "general",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "general"
      }
    ],
    "core_ml_enabled": false
  },
  {
    "classifier_id": "explicit",
    "name": "explicit",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "explicit"
      }
    ],
    "core_ml_enabled": false
  },
  {
    "classifier_id": "food",
    "name": "food",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "food"
      }
    ],
    "core_ml_enabled": false
  }
]}

My attempt to merge these two JSONs is as follows:

respArray = []
      var defaultClassifiers = constants.defaultClassifiers.classifiers
      respArray.push(defaultClassifiers,respBody.classifiers)
      respBody = respArray
      if (respBody.length > 0) {
        respBody = applyPagination(respBody, reqParams.filter, options)
      }

The current output obtained is:

[
{
    "0": {
        "classifier_id": "general",
        "name": "general",
        "status": "ready",
        "owner": "",
        "created": "",
        "updated": "",
        "classes": [
            {
                "class": "general"
            }
        ],
        "core_ml_enabled": false
    },
    "1": {
        "classifier_id": "explicit",
        "name": "explicit",
        "status": "ready",
        "owner": "",
        "created": "",
        "updated": "",
        "classes": [
            {
                "class": "explicit"
            }
        ],
        "core_ml_enabled": false
    },
    "2": {
        "classifier_id": "food",
        "name": "food",
        "status": "ready",
        "owner": "",
        "created": "",
        "updated": "",
        "classes": [
            {
                "class": "food"
            }
        ],
        "core_ml_enabled": false
    }
},
{
    "0": {
        "classifier_id": "link_877889562",
        "name": "link",
        "status": "ready",
        "owner": "",
        "created": "2019-07-05T04:10:06.457Z",
        "updated": "2019-07-05T04:10:06.457Z",
        "classes": [
            {
                "class": "classcreatezip1"
            }
        ],
        "core_ml_enabled": true
    },
    "1": {
        "classifier_id": "classifer1807",
        "name": "classifer1807",
        "status": "ready",
        "owner": "",
        "created": "2019-07-25T10:43:00.012Z",
        "updated": "2019-07-25T10:43:00.012Z",
        "classes": [
            {
                "class": "class18"
            }
        ],
        "core_ml_enabled": true
    }]

Expected output was:

[
  {
    "classifier_id": "general",
    "name": "general",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "general"
      }
    ],
    "core_ml_enabled": false
  },
  {
    "classifier_id": "explicit",
    "name": "explicit",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "explicit"
      }
    ],
    "core_ml_enabled": false
  },
  {
    "classifier_id": "food",
    "name": "food",
    "status": "ready",
    "owner": "",
    "created": "",
    "updated": "",
    "classes": [
      {
        "class": "food"
      }
    ],
    "core_ml_enabled": false
  },
  {
    "classifier_id": "improper",
    "name": "improper",
    "owner": "",
    "status": "failed",
    "core_ml_enabled": true,
    "explanation": "",
    "created": "2019-07-04T14:28:37.402Z",
    "classes": [
        {
            "class": "impropertest"
        }
    ],
    "updated": "2019-07-04T14:28:37.402Z"
},
{
    "classifier_id": "improper",
    "name": "improper",
    "owner": "",
    "status": "failed",
    "core_ml_enabled": true,
    "explanation": "",
    "created": "2019-07-05T08:31:55.463Z",
    "classes": [
        {
            "class": "impropertest"
        }
    ],
    "updated": "2019-07-05T08:31:55.463Z"
}]

It seems like the merging process went wrong causing the array to display with numerical keys. I'm unsure of my mistake here.

Answer №1

When working with JSON, remember that you are not inputting individual objects. Instead, you are inputting an array where each index contains an object with its own set of properties.

Think of the numbers as the locations within the array, also known as array indices.

Answer №2

It seems that you are uncertain about the functionality of the applyPagination function. Based on my understanding, it likely takes an array of classifiers and filters them based on certain parameters.

If you want to add the default classifiers to the response classifiers, you can follow this approach:

const defaultClassifiers = constants.defaultClassifiers.classifiers;
const responseClassifiers = respBody.classifiers;
let respBody = defaultClassifiers.concat(responseClassifiers);
if (respBody.length > 0) {
    respBody = applyPagination(respBody, reqParams.filter, options)
}

Answer №3

You can easily accomplish this using the es6 copy operator.

 const defaultArr = [
  {
    classifier_id: 'general',
    name: 'general',
    status: 'ready',
    owner: '',
    created: '',
    updated: '',
    classes: [
      {
        class: 'general',
      },
    ],
    core_ml_enabled: false,
  },
  {
    classifier_id: 'explicit',
    name: 'explicit',
    status: 'ready',
    owner: '',
    created: '',
    updated: '',
    classes: [
      {
        class: 'explicit',
      },
    ],
    core_ml_enabled: false,
  },
  {
    classifier_id: 'food',
    name: 'food',
    status: 'ready',
    owner: '',
    created: '',
    updated: '',
    classes: [
      {
        class: 'food',
      },
    ],
    core_ml_enabled: false,
  },
];

const result = [{
  classifier_id: 'improper',
  name: 'improper',
  owner: '',
  status: 'failed',
  core_ml_enabled: true,
  explanation: '',
  created: '2019-07-04T14:28:37.402Z',
  classes: [
    {
      class: 'impropertest',
    },
  ],
  updated: '2019-07-04T14:28:37.402Z',
},
{
  classifier_id: 'improper',
  name: 'improper',
  owner: '',
  status: 'failed',
  core_ml_enabled: true,
  explanation: '',
  created: '2019-07-05T08:31:55.463Z',
  classes: [
    {
      class: 'impropertest',
    },
  ],
  updated: '2019-07-05T08:31:55.463Z',
}];

const finalArray = [...defaultArr, ...result];

const defaultArr = [
  {
classifier_id: 'general',
name: 'general',
status: 'ready',
owner: '',
created: '',
updated: '',
classes: [
  {
    class: 'general',
  },
],
core_ml_enabled: false,
  },
  {
classifier_id: 'explicit',
name: 'explicit',
status: 'ready',
owner: '',
created: '',
updated: '',
classes: [
  {
    class: 'explicit',
  },
],
core_ml_enabled: false,
  },
  {
classifier_id: 'food',
name: 'food',
status: 'ready',
owner: '',
created: '',
updated: '',
classes: [
  {
    class: 'food',
  },
],
core_ml_enabled: false,
  },
];

const result = [{
  classifier_id: 'improper',
  name: 'improper',
  owner: '',
  status: 'failed',
  core_ml_enabled: true,
  explanation: '',
  created: '2019-07-04T14:28:37.402Z',
  classes: [
{
  class: 'impropertest',
},
  ],
  updated: '2019-07-04T14:28:37.402Z',
},
{
  classifier_id: 'improper',
  name: 'improper',
  owner: '',
  status: 'failed',
  core_ml_enabled: true,
  explanation: '',
  created: '2019-07-05T08:31:55.463Z',
  classes: [
{
  class: 'impropertest',
},
  ],
  updated: '2019-07-05T08:31:55.463Z',
}];

const finalArray = [...defaultArr, ...result];
console.log(finalArray);

By following these steps, you will achieve the desired outcome. Enjoy your coding journey! :)

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 implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

Is it necessary for the structure of your result to perfectly match the JSON passed in when using json.Unmarshal?

I have a JSON string that needs to be unmarshaled: { "id":1720, "alertId":1, "alertName":"{stats} Test Lambda Alert", "dashboardId":5, "panelId":2, "userId":0, "newState":"alerting", "prevState":"ok", "time":1523983581000, "text":"", ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Tips for using a JavaScript variable in a PHP file on WordPress

As a newcomer to Wordpress, I am trying to navigate the Theme Editor. Within it, I found a javascript file that looks like this: const isMenuOpen = false; function toggleMenu() { alert("toggle"); isMobileMenuOpen = !isMobileMenuOpen; } ...

Running various IT blocks within a Protractor loop to enhance web testing

After logging in to a web page, we need to use a for loop to perform multiple tests on the page. The ideal test scenario involves a table with buttons on each row that leads to another page where data needs to be validated. Currently, all expectations and ...

jQuery Typeahead implementation malfunctioning when text matches either the first or last character

It seems like there is a problem with the .split() method, especially when the characters match the beginning or end of a name. To see the issue in action, visit this JSFiddle link: http://jsfiddle.net/5uebxvex/ I'm working with the Employees tabl ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

What is the best way to modify an array's property in order to achieve the desired outcome when using json_encode?

Expected Result ['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50'] The output I am receiving is as follows: ["'#ff0000','#4caf5 ...

jQuery's element loading function fails to work with ajax requests

When trying to preload ajax data before attaching it to a div, I utilized the following code: $.ajax({ url: 'ajax.php', data: { modelID:id }, type: 'post', success: function(result){ $(result).load(function(){ ...

Exporting a function from one module does not automatically make it accessible in another module

I'm stuck trying to call the retrieve_endpoints function from cli_config.js. I made sure to add the functions to the module exports and included the require statement in the cli_config file. But for some reason, I can't seem to access the retriev ...

Issue encountered while trying to exhibit jpg image content from server side on html

I am attempting to display an image from server-side data using an Ajax call. The data stored on the server looks something like this: "ÿØÿàJFIFÿÛC4­¶¸UOHlʵcBò)3¹_È'I4~&éüÿ§Ú<ã©ã4>'Øù¿ÇÄmËCÈgÚsZ¥ë" Upo ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

How can I exclude a specific JavaScript asset file in Symfony2?

My default setup includes loading all scripts into the head section from the js/ folder. However, I need to exclude one specific script file from being loaded with the others. How can I achieve this? Code base.html.twig .... {% block javascripts %} { ...

"Converting Python string to a bytearray: A step-by-step guide

I am currently working with Python 2.7 and I have a situation where I need to convert the return value of the struct.pack() function, which is of type str according to the documentation, into a bytearray object. The issue arises from the fact that the buil ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

Error: Material-UI X is unable to locate the data grid context

Utilizing the Data Grid Pro feature from Material-UI in my React application. I attempted to craft a personalized toolbar for the DataGridPro component by incorporating the GridToolbarColumnsButton, GridToolbarFilterButton, GridToolbarDensitySelector, and ...

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...