Home > Software engineering >  How to check if array contain json object or not using javascript / node js
How to check if array contain json object or not using javascript / node js

Time:03-24

Is there any possible way I can check that Array contain json object or not

like this is my data which I want to test when I do console I get this data so

[{system:{software:check, hardware:check}}]
[[value1,value2],[value3,value4]]
[testing, free-test]
[{system:{software:uncheck, hardware:uncheck}}]
[dummy, test]
[true,false]

like to test this I wrote this code

but I think this is the lengthiest process to check if the array contain json object or not I have heard about includes but don't know how to use to include to check if the json present in array or not

let data = [{ system: { software: "check", hardware: "check" } }];
data.forEach((type) => {
      if (typeof type === "object") {
        console.log("yes it has json object");
      } 
      else if(Array.isArray(type)){
      console.log("yes it has array")
      }
      else {
        console.log("no it don't have json object");
      }
})

CodePudding user response:

First of all checking whether something is an object is not as straightforward as it seems to be. Look at this answer for more details.

Checking for typeof variable == "object" is not enough, we need to check for null and !Array.isArray(variable) as well. I've factored this out to function isObject() which I will be using throughout this post.

/**
 * Checks if a variable is a JavaScript object.
 * Check is performed as recommended here https://stackoverflow.com/a/8511350/17487348.
 * @param {any} variable
 * @returns
 */
function isObject(variable) {
  return (
    typeof variable === "object" &&
    !Array.isArray(variable) &&
    variable !== null
  );
}

Then as outlined in my comment already there are many options depending on whether you want to check if any or all elements of the array are objects. And there is the possibility to return true or false for each element of the array.

Here a short program which illustrates all options with different inputs and displays the result.

/**
 * Run all three possible results to illustrate how they work.
 * @param {any[]} array array with elements
 */
function allPossibilites(array) {
  // check whether all elements are objects
  const every = array.every((item) => isObject(item));
  // check whether one of them is an object
  const some = array.some((item) => isObject(item));
  // return true or false for every element
  const all = array.map((item) => isObject(item));

  console.log(`
  Array: ${JSON.stringify(array)}
  - All elements are objects?                    \t${every}
  - At least one element is an object?          \t${some}
  - Tell me for each element if it is an object?\t${JSON.stringify(all)}
  `)
}

/**
 * Checks if a variable is a JavaScript object.
 * Check is performed as recommended here https://stackoverflow.com/a/8511350/17487348.
 * @param {any} variable
 * @returns
 */
function isObject(variable) {
  return (
    typeof variable === "object" &&
    !Array.isArray(variable) &&
    variable !== null
  );
}

const arr1 = [{}, ""];
const arr2 = [{}, {}];
const arr3 = [1, 2]
const arr4 = [[], []]

allPossibilites(arr1);
allPossibilites(arr2);
allPossibilites(arr3);
allPossibilites(arr4);

Note: If you comment out the following line !Array.isArray(variable) && in isObject() you will see that arr4 is now considered to contain objects even though it contains arrays. This illustrates that checking for typeof variable === "object" is not enough.

CodePudding user response:

You can iterate through the array and see if an object appears, and using instanceof identify if it's an object.

data.forEach(d => {
    if (d instanceof Object) //has an object
});
  • Related