Converting an array into an object using Javascript, with the exclusion of any 0 (zero) values

I've encountered a problem where my array is getting remapped into an object, but it's excluding the 0 (zero) values. I need to include these zero values in the final object. How can I adjust my code to achieve this? Your help is much appreciated! :)

Here is my array:

var data = {
"queryInfo": {
    "totalRows": "18"
},
    "resultset": [
    ["A", "MAXI", "ACC - GC", "SER", 5646.5],
    ["A", "MAXI", "ACC - SACC", "KIT", 2474.93],
    ["A", "MAXI", "ACC - SACC", "NET", 5418.72],
    ["A+", "MAXI", "ACC - DIV", "FORM", 1531.04],
    // more array elements...
],
    "metadata": [{
    "colIndex": 0,
        "colType": "String",
        "colName": "CP"
}, {
    "colIndex": 1,
        "colType": "String",
        "colName": "ST"
}, {
    // more metadata elements...
}]
};

and here is my function:

function recom(resultset) {
  var obj = {};
  for (var j = 0; j < resultset.length; j++) {
    if (resultset[j]) {
        obj[data.metadata[j].colName] = resultset[j];
    }
  }
  return obj;
}
var arr = [];
for (var i = 0; i < data.resultset.length; i++) {
  if (data.resultset[i] !== null) {
    arr.push(recom(data.resultset[i]));
  }
}

The issue occurs when a value of 0 in index 4 of `data.resultset` causes my function to skip that level in the final object. The correct output should retain the value as shown below:

Correct result: {"CP":"A+","ST":"MAXI","GR":"SCC","PR":"HEL","VALUE":0}

I want my function to work correctly even with 0 values included. Any suggestions on how to fix this would be highly appreciated.

Thank you for your assistance.

Answer №1

Adjust the condition in recom to specifically validate zero:

Instead of the current code:

if (resultset[j])

Consider using:

if (resultset[j] === 0 || resultset[j])

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

Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server. Here is the link to the JSON server documentation: JSON Server Documentation To see a dem ...

Can you show me a way to smoothly fade out a selected element upon clicking with jQuery?

I am currently working on a jQuery function that will fade out a specific element when the user clicks on it within the webpage. Initially, I attempted to use the universal selector to target all elements, but this resulted in every element on the page fa ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

Implementing server-side functionality for adding new records in DataTables (CRUD) operations

My goal is to utilize the DataTables (CRUD) plugin available on DataTables Data Manager (CRUD) Add-on Everything seems to be functioning correctly except when attempting to add a new record. I have followed the instructions provided in the example links A ...

What is the best way to recycle or invoke a function in Angular from a different file?

I have a function in file1.ts that acts as a converter. I am looking to reuse this function in file2.ts. Any suggestions or ideas? Thank you! #Code formatBytes(bytes, decimals = 2) : string | number { console.log("lol") if (bytes === 0) { r ...

What is the best way to determine total revenue by consolidating data from various tables within an IndexedDB database?

Seeking guidance on building a stock/sales application in JavaScript with Dexie.js. I need assistance in efficiently calculating the Total Sales amount without resorting to overly complicated recursive code that triggers multiple queries for a single produ ...

How can one elegantly deal with invalid arguments in JavaScript?

Imagine a scenario where I have a function that specifically accepts non-negative numbers, but is given a negative argument. If this were in Python, I would raise a ValueError. In Java, an IllegalArgumentException would be thrown. Is there a built-in exce ...

Capture HTML content as a string in Metor and then transform it into a DOM element at a later time

I need to store a string, such as "<div class='some_class'>some content</div>", in a mongo document. Later on, I want to retrieve this content and convert it into a DOM node. What is the best way to manipulate the content before inse ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

Deleting a nested object from an array within another object

Recently, I delved into the world of Redux and have found it quite fascinating. However, I am currently facing a dilemma where my new reducer function inadvertently changes the type of a state variable, which is not what I intended. The desired structure ...

Calculate the total values of nested objects within an array of objects

I encountered an array of objects with various properties - [{ title: "oranges", id: 5802537, cart: { purchased: 3, stockTotal: 9 }, price: 3, department: "fresh fruit and veg" }, { title: &qu ...

Continuously examine whether all elements within a multi-layered array of unknown depth are void

I am facing an issue with determining if all the values in a multidimensional array posted to my PHP script are empty or not. Below is the array structure: $array = [ [ 'a' => '', 'b' => [ ...

Is there a way to activate a function when clicking on the "View larger map" option within the Google Maps

I am currently in the process of creating a cordova application with ionic and angularjs, where I am using the google maps embed API to include a map within the app. https://developers.google.com/maps/documentation/embed/guide https://i.sstatic.net/TOd ...

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...

I'm puzzled as to why my get request seems to be hit-or-miss, working at times but returning a 404 not found error at other

Currently in the process of learning Angular and working on a project that involves a MongoDB database and Express for APIs. I am trying to retrieve comments for a specific post using the post ID. The GET request should return a list of comments, but the ...

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

Adding new elements to a blank numpy array

Hello there, I am currently attempting to transform the following array using Manhattan distance: test=np.array([[0,0],[0,1],[1,1],[3,0]]) The goal is to convert it into this shape: [0., 1., 2., 3.] [1., 0., 1., 4.] [2., 1., 0., 3., [3., 4., 3., 0.] Her ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Create dynamic connections between animated sprites using Three.js

I am attempting to insert lines between animated sprites, similar to the example provided. Despite trying various solutions, I have been unsuccessful in creating either a dynamic or static line between these animated sprites. Is it feasible to generate a d ...

Working with Ruby: Retrieving keys from an array that is nested within a hash

I'm in the process of developing a compact video game for the console, where I've created a primary configuration hash to hold various game values. However, when attempting to access keys within an array in that hash, no values are being returned ...