Employing square brackets for accessing JSON data in JavaScript

I am facing a requirement where I need to extract the value of the JSON data based on the column specified by the user.

for (var k = 0; k < arr.length; k++) {
    for (var i = 0; i < checkedFilters.length; i++) {
        console.log("value[columnName]", arr[k][columnName]);
        if ((arr[k][columnName] == checkedFilters[i])) {
            temporaryFilterData.push(arr[k]);
        }
    }
}

The user will pass the columnName in a function, however, whenever I try to access arr[k][columnName], it only gives me the very first value of the array. What could be causing this issue?

JSON

 [
        {
            id: 1,
            type: 1,
            typeName: "Lead",
            client: 1,
            clientName: "Ljungbloms Elektriska AB",
            marking: "Marking for Ljungbloms Elektriska AB",
            status: 2,
            statusName: "Open",
            stage: 2,
            stageName: "Stage 2",
            leadValue: 1,
            probability: 1,
            issuer: 1,
            issuerName: "Sales",
            handler: 1,
            handlerName: "Sales",
            created: 1462345200000,
            createdString: "2016-05-04"
        },
        {
            id: 5,
            type: 1,
            typeName: "Lead",
            client: 1,
            clientName: "Ljungbloms Elektriska AB",
            marking: "Marking for Ljungbloms Elektriska AB",
            status: 2,
            statusName: "Open",
            stage: 2,
            stageName: "Stage 2",
            leadValue: 1,
            probability: 1,
            issuer: 1,
            issuerName: "Sales",
            handler: 1,
            handlerName: "Sales",
            created: 1462345200000,
            createdString: "2016-05-04"
        },
        {
            id: 2,
            type: 1,
            typeName: "Lead",
            client: 2,
            clientName: "Solina Sweden AB",
            marking: "Marking for Solina Sweden AB",
            status: 1,
            statusName: "Closed",
            stage: 3,
            stageName: "Stage 3",
            leadValue: 1,
            probability: 1,
            issuer: 1,
            issuerName: "Sales",
            handler: 1,
            handlerName: "Sales",
            created: 1462345200000,
            createdString: "2016-05-04"
        },
        {
            id: 3,
            type: 2,
            typeName: "Opportunity",
            client: 3,
            clientName: "H & M Hennes & Mauritz GBC AB",
            marking: "Marking for H & M Hennes & Mauritz GBC AB",
            status: 3,
            statusName: "Pending",
            stage: 4,
            stageName: "Stage 4",
            leadValue: 1,
            probability: 1,
            issuer: 1,
            issuerName: "Sales",
            handler: 1,
            handlerName: "Sales",
            created: 1462345200000,
            createdString: "2016-05-04"
        }
     ];

checkedFileter Array

["Open", "Unset","Closed"]

result JSON

[{
                id: 1,
                type: 1,
                typeName: "Lead",
                client: 1,
                clientName: "Ljungbloms Elektriska AB",
                marking: "Marking for Ljungbloms Elektriska AB",
                status: 2,
                statusName: "Open",
                stage: 2,
                stageName: "Stage 2",
                leadValue: 1,
                probability: 1,
                issuer: 1,
                issuerName: "Sales",
                handler: 1,
                handlerName: "Sales",
                created: 1462345200000,
                createdString: "2016-05-04"
            },
            {
                id: 5,
                type: 1,
                typeName: "Lead",
                client: 1,
                clientName: "Ljungbloms Elektriska AB",
                marking: "Marking for Ljungbloms Elektriska AB",
                status: 2,
                statusName: "Open",
                stage: 2,
                stageName: "Stage 2",
                leadValue: 1,
                probability: 1,
                issuer: 1,
                issuerName: "Sales",
                handler: 1,
                handlerName: "Sales",
                created: 1462345200000,
                createdString: "2016-05-04"
            },
            {
                id: 2,
                type: 1,
                typeName: "Lead",
                client: 2,
                clientName: "Solina Sweden AB",
                marking: "Marking for Solina Sweden AB",
                status: 1,
                statusName: "Closed",
                stage: 3,
                stageName: "Stage 3",
                leadValue: 1,
                probability: 1,
                issuer: 1,
                issuerName: "Sales",
                handler: 1,
                handlerName: "Sales",
                created: 1462345200000,
                createdString: "2016-05-04"
            }]

ColumnName is a variable that serves as a placeholder for the column name. For example, statusName.

Therefore, the condition will now specifically check for the statusName in the JSON elements.

Answer №1

Consider utilizing more appropriate array methods, such as Array#filter and Array#some. This can optimize the iteration process by stopping as soon as a value is found, especially when the desired result is a subset of the original array.

var arr = [{ id: 1, type: 1, typeName: "Lead", client: 1, clientName: "Ljungbloms Elektriska AB", marking: "Marking for Ljungbloms Elektriska AB", status: 2, statusName: "Open", stage: 2, stageName: "Stage 2", leadValue: 1, probability: 1, issuer: 1, issuerName: "Sales", handler: 1, handlerName: "Sales", created: 1462345200000, createdString: "2016-05-04" }, { id: 5, type: 1, typeName: "Lead", client: 1, clientName: "Ljungbloms Elektriska AB", marking: "Marking for Ljungbloms Elektriska AB", status: 2, statusName: "Open", stage: 2, stageName: "Stage 2", leadValue: 1, probability: 1, issuer: 1, issuerName: "Sales", handler: 1, handlerName: "Sales", created: 1462345200000, createdString: "2016-05-04" }, { id: 2, type: 1, typeName: "Lead", client: 2, clientName: "Solina Sweden AB", marking: "Marking for Solina Sweden AB", status: 1, statusName: "Closed", stage: 3, stageName: "Stage 3", leadValue: 1, probability: 1, issuer: 1, issuerName: "Sales", handler: 1, handlerName: "Sales", created: 1462345200000, createdString: "2016-05-04" }, { id: 3, type: 2, typeName: "Opportunity", client: 3, clientName: "H & M Hennes & Mauritz GBC AB", marking: "Marking for H & M Hennes & Mauritz GBC AB", status: 3, statusName: "Pending", stage: 4, stageName: "Stage 4", leadValue: 1, probability: 1, issuer: 1, issuerName: "Sales", handler: 1, handlerName: "Sales", created: 1462345200000, createdString: "2016-05-04" }],
checkedFilters = ["Open", "Unset", "Closed"],
columnName = 'statusName',
temporaryFilterData = arr.filter(function (a) {
return checkedFilters.some(function (b) {
return a[columnName] == b;
});
});

console.log(temporaryFilterData);

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

Solving the pyramid of doom with Node.js

I have been struggling to find a way to simplify my code structure. Here is what I have come up with so far: router.use('/create', function(res,req,next) { try { var data = { startDate: new Date(req.body. ...

Building a div element within a React function

For an exercise, I need to create an input field and a button. The goal is to display the text from the input field in a div/span below when the button is clicked. If I change the text in the input field and click the button again, the displayed text shoul ...

Header reference differs from the document referrer

this is the request header: GET / HTTP/1.1 Host: localhost:3002 Connection: keep-alive sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 User-Agent: ...

Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following: const products = await Product.find({ &apo ...

Each occurrence of a variable update will result in the storing of its value within an

I'm struggling to include a variable in an array without it changing. Every time I try to push the variable to the array, it seems to alter. i = 10; function addToArray() { let b = []; b.push(i); console.log(b); } addToArray(); The variable n ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

Display only a loading image with a see-through background after submitting the page

After submitting the page, I would like to display a loading image in the middle of the page with a transparent background. The current styling code I have used is as follows: #loading { position: fixed; top: 50%; left: 50%; z-index: 1104; ...

Encountering timeout issues while implementing routes in VueJS

Currently, I am utilizing VueJS to send data to the server and then navigate to another route. I attempted the following code: saveSupportArea: function () { this.toast("success"); var that = this; setTimeout(function(that){ that.$rou ...

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...

Is there a way to programmatically fetch files from a MySql / Node.js server?

I've been working on my CRUD app and I'm currently focusing on downloading files from a MySql Nodejs server. Here are the steps I have accomplished so far: I created a function in userContoller.js to query the MySql database for the id=179 (just ...

React Error boundary is failing to perform as anticipated

Having issues implementing an error boundary in React. Here is the code snippet: ErrorBoundary.js import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: fal ...

Create div elements using JSX and add them to an array

I am working with a structure that looks like this: var circle = { 'one': {items: []}, 'two': {items: []}, 'three': {items: []}, 'four': {items: []} }; Each items array needs to contain 10 unique ...

Encountering an issue with undefined property while trying to push in Angular

Having trouble updating a json file with attributes and encountering an error... Error Message: TypeError: Cannot read property 'push' of undefined This snippet shows my controller logic... 'use strict'; (function () { var userQuote ...

Monitor JSON for updates on Firebase, then effortlessly send notifications

LATEST UPDATE: After considering all the feedback received, it seems like Firebase is the most suitable solution for various reasons. However, I am still unsure about how to monitor the change in my json file from firebase specifically when the course is ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

"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 ...

What is the reason behind the decision for Google Chart API to display a legend only for pie charts

I have encountered an issue while attempting to display a pie chart on an ASP.NET webpage using the provided URL: . Despite passing valid values in the URL parameters, only the legend of the chart is displayed and not the chart itself. Can anyone provide i ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...