Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop?

My main goal is to iterate through the objects contained within the JSON.

  • I attempted if(json.length!=3) but encountered failure when reaching the object, presumably due to the lack of length property for the object
  • Another approach was using
    json.hasOwnProperty("field_id")
    , which failed at encountering the string "and"
  • Using if(json.length=undefined) also did not work as the length ended up becoming undefined itself

Below is my JSON data:

[
    {
        "field_id": 122,
        "operator_id": "1",
        "where_flag": true
    "and",
    {
        "field_id": 128,
        "operator_id": "0",
        "where_flag": true
    },
    "and",
    {
        "field_id": 148,
        "operator_id": "1",
        "where_flag": true
    }
]

Answer №1

To optimize your process, my suggestion is to initially filter the items before proceeding with a loop:

function checkIfObject(data) {
  return typeof data === "object" && data !== null;
}

array.filter(element => checkIfObject(element)).forEach(...)

Alternatively, you could consolidate both steps into a single loop (although this approach is not typically recommended):

array.forEach(element => {
  if(!checkIfObject(element)) return;

  ...
})

Answer №2

Perhaps this solution will do the trick:

let data = [
    {
        "field_id": 122,
        "operator_id": "1",
        "where_flag": true
    },
    "and",
    {
        "field_id": 128,
        "operator_id": "0",
        "where_flag": true
    },
    "and",
    {
        "field_id": 148,
        "operator_id": "1",
        "where_flag": true
    }
]

data.forEach((element)=>{
    if(typeof(element)=="object"){
        console.log(element)
    }
})

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

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

Having trouble displaying the name and pricing

Can someone help me troubleshoot an issue with fetching data from this website? Here is the link . When I hit request to fetch the data, no data is being printed. import requests import time url = "https://www.adidas.com/api/metadata/pdp?" # ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

Guide to Retrieving Response Data and Converting it into HTTP Header Manager in JMeter

After running the Login sampler, I received the following result: [Login Sampler Result Data][1] In this output, I need to extract "access_token":"91kLM68tdMBoDFRURArvdmwYgWV9Nr2sHYDwivTM" and store the value "91kLM68tdMBoDFRURArvdmwYgWV9Nr2sHYDwivTM" ...

Injecting Ajax-loaded content into an HTML modal

Hey there! I'm currently working on a project involving the IMDb API. The idea is that when you click on a film title, a popup should appear with some details about the movie. I've made some progress, but I'm stuck on how to transfer the mov ...

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

Utilizing express-session and passport to initiate a new session for each request

Currently working on developing an e-commerce platform, both front and back-end. Using express and passport for a basic login/register system. The issue I'm facing is that every time a page with a request is accessed, a new session is created and stor ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Tips on using jQuery to horizontally align an element in the viewport

Although this question has been raised before, my situation is rather unique. I am currently constructing an iframe for future integration into a slideshow component on the website. The challenge lies in the fact that I have a dynamically sized flexbox th ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

Sending a File Object and Data to an MVC 6 Controller in ASP.NET 5 using JavaScript

I have been working with an Ajax function that is supposed to handle file upload, but I am encountering some issues. Despite dragging and dropping the file, nothing seems to happen with the Ajax. Upon inspecting the properties on the page, I can see that t ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

Achieving the validation with a bold red border

Hi, I'm currently learning React and I've been using regular JavaScript to validate my form. Here's a snippet of how I'm doing it: <TextField label="Title" variant="outlined" si ...

Using `require(variable)` is not functional in next-js environment

I'm attempting to display an image using the next-optimised-images module. When I try to include images like this: <img src={require(c.logo)} alt={c.title} /> I encounter the following error: https://i.stack.imgur.com/Jtqh9.png However, when ...