Extract the array of numbers from the JSON file

My task is to extract an array of numbers from JSON files. I need to handle files that contain only arrays of numbers or one level deeper (referred to as direct arrays). These files may also include other data types such as strings or booleans.

The challenge lies in identifying the array of numbers, as they may be classified as objects when their type is checked.

I must solve this without using any additional libraries. Is there a standard solution available for this issue?

file1.json

[1,2,3,4]

Output:

1,2,3,4

file2.json

{a:'4',b:true,c:[5,6,7]}

Output:

5,6,7

file3.json

{a:[1,'2',3],b:2,c:['1','2','3']}

Output:

[]

The goal is to fulfill a Promise with the sum of numbers extracted and reject it if there are no arrays of numbers or if the JSON files are invalid.

Answer №1

When performing a surface level iteration on the object, it becomes essential to distinguish between an object and an array before examining number arrays within. By looping through an array, one can validate each element as a number using the typeof operator. The provided function accepts an object as input and generates an array consisting of number arrays found in the object.

var array1Example = [1, 2, 3];
var array2Example = [1, '2', 3, 'a'];
var object1Example = {
  a: '4',
  b: true,
  c: [5, 6, 7]
};
var object2Example = {
  a: [1, '2', 3],
  b: 2,
  c: ['1', '2', '3']
}


function isArrayOfNumbers(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] !== 'number') {
      return false;
    }
  }

  return true;
}

function getNumberArrays(obj) {
  var numArrays = [];
  if (Array.isArray(obj)) {
    if (isArrayOfNumbers(obj)) {
      numArrays.push(obj);
    }
  } else if ((typeof obj === "object") && (obj !== null)) {
    for (var key in obj) {
      if (Array.isArray(obj[key]) && isArrayOfNumbers(obj[key])) {
        numArrays.push(obj[key]);
      }
    }
  }

  return numArrays;
}

console.log(getNumberArrays(array1Example));
console.log(getNumberArrays(array2Example));
console.log(getNumberArrays(object1Example));
console.log(getNumberArrays(object2Example));

Answer №2

This method employs recursive techniques to scan for nested arrays.

var arr = ['[1,2,3,4]','{"a":"4","b":true,"c":[5,6,7]}','{"a":[1,"2",3],"b":2,"c":["1","2","3"]}','{xds}'];
var index, subIndex, len = arr.length;

function checkForArray(value, depth) {
        var element, filteredArr;
        
        if (depth > 1) {
                return false;
        }
        
        if (Array.isArray(value)) {
                filteredArr = value.filter( function(element) {
                        return (isNaN(element) || typeof element === "string");
                });
                
                if (filteredArr.length === 0) {
                        return true;
                } else {
                        return false;
                }
        } else {
        
                if (typeof value === "object") {
                        for (element in value) {
                                if (checkForArray(value[element], depth+1) === false) {
                                        return false;
                                }
                        }
                        return true;
                }
        }
        
        return null;
}

for (index = 0; index < len; index++) {
        console.log(arr[index]);
        try {
                subIndex = JSON.parse(arr[index]);
                console.log(checkForArray(subIndex, 0));
        } catch (error) {
                console.log('Error caught: '+ error);
        }
}

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

Utilize Oracle 18 to efficiently extract data from JSON using the json_table function

Here is a sample request: with j (sJson) as ( select '{ "ID":"1444284517", .... )) jt In column, different fields may be present. How can all fields in columns be listed without specifying the type a ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

Unforeseen outcomes of JavaScript when using the let and var keywords

In JavaScript, when using the var keyword to declare a variable, the JS engine assigns a default value of "undefined" at creation stage. console.log(message); // undefined var message = "My message"; However, with the let keyword: console.log(message); ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...

Exploring the benefits of WordPress integration with form caching and dynamic show/hide div

Within my Wordpress (3.8.1) website, I have created a form that includes a checkbox. When this checkbox is clicked, a hidden div appears on the screen, prompting users to provide additional information. The JavaScript code responsible for showing the hidd ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

Using AngularJS to send a $http.post request with Paypal integration

This form utilizes the standard PayPal format for making purchases. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="<a href= ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

Show a Pair of Images Upon Submission Utilizing Ajax

Imagine having two separate div containers displayed as shown below: What I achieved was clicking the submit button would upload the image to the designated area. However, my goal is for a single click on the button to load the image in both containers. ...

The function JSON.parse appears to be malfunctioning within the code, yet it operates smoothly when executed in

I am facing an issue with my Angular $http post service that communicates with a WCF service. The success handler in the http post is as follows: .success(function (data) { var response = JSON.parse(data); var tsValid = response.Outcome; defer ...

When using node.js, the Ajax success function is not being executed

Why doesn't success respond? Here is the code I've used: Client-side code: function add(){ var values = formserial(addd); var tok = "abc", var url= 'http://localhost:8181/add'; $.ajax({ type: "POST", ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

The issue arises when attempting to render an SVG with JavaScript embedded inside using the img, object, or

Issue with the title ... please follow these steps: (view codes below) Create an svg + open it separately (name it keysaway.svg) Create html + open it individually When you observe, the svg displays a simple up and down animation but fails to work when l ...

The visibility feature in knockout.js appears to be malfunctioning

I am relatively new to using knockout.js and I'm attempting to control the visibility of a label on a slider item based on a specific condition. Even when the condition is false, the label still appears. Any suggestions would be greatly appreciated. ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

Beginner Query: What is the method for retrieving this data in JavaScript?

I'm struggling with accessing a specific value in an Object in JavaScript for the first time. The JSON I'm working with is structured like this: { "payload":{ "params":{ "switch:0":{ &q ...

What is the best way to select an element with a dynamic ID in jQuery?

I'm encountering an issue when passing the ID through a directive. I'm unable to access the element using jQuery within the Link function, even though the element is receiving the correct dynamic ID as a parameter: Here's the Directive: (f ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...