Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array?

I attempted the following:

const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll()
    .filter(landlinedRates => landlinedRates["fiberAgrupations"].includes(this.myPackId));

myPackId is 3230 and can be found in the first object.

JSON:

[{
            "id": "T300Mb2",
            "idAdditionalImage": "",
            "name": "300 Mb",
            "sourceId": ["T300Mb2"],
            "fiberAgrupations": ["3230","3232","3234","3235","3237","3239","3248","3250","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "34,95"},
              {"id": "3156", "price": "39,95"},
            ],
            "availableRates": ["T600Mb2", "T1Gb"]
         },
         {
            "id": "T600Mb",
            "idAdditionalImage": "",
            "name": "600 Mb",
            "sourceId": ["T600Mb"],
            "fiberAgrupations": ["2989","2994","2982","2983","3090","3089","3093","3084","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "38,95"},
              {"id": "3156", "price": "47,95"},
            ],
            "availableRates": []
         },
         {
            "id": "T600Mb2",
            "idAdditionalImage": "",
            "name": "600 Mb",
            "sourceId": ["T600Mb2"],
            "fiberAgrupations": ["3219","3220","3223","3224","3241","3244","3252","3255","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "38,95"},
              {"id": "3156", "price": "43,95"},
            ],
            "availableRates": ["T1Gb"]
         }]

Answer №1

Locate will identify the first item in an array that meets the specified condition. Screen will create a new array containing all items from the original array that meet the specified condition.

Put simply:

const prices = [{
    'id': 'T300Mb2',
    'fiberAgrupations': ['3230', '3232']
  },
  {
    'id': 'T600Mb',
    'fiberAgrupations': ['2989', '2994']
  },
  {
    'id': 'T600Mb2',
    'fiberAgrupations': ['3219', '3220'],
  }];

const myPackId = '3230';
const output = prices.filter(landlinedRates =>
 landlinedRates['fiberAgrupations'].includes(myPackId)
);
console.log(output);

outputs:

[ 
   { 
    id: 'T300Mb2', 
    fiberAgrupations: [ '3230', '3232' ]
   } 
]

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

JSON.parse has thrown an unexpected token error with 'e'

Attempting to retrieve information from a JSON object stored in a file using FileReader. The contents of the json file are as follows: {"markers": [ { "point":new GLatLng(40.266044,-74.718479), "homeTeam":"Lawrence Library ...

Performing a JSON GET request in Python is similar to using cURL

I have a command using cURL that I want to convert into Python. curl -XGET "http://localhost:9200/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search" -H 'Content-Type: application/json' -d' { "query": { "regexp": { ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

Extract the JSON information to find the <highlighting> tag used to emphasize text within a specific field

{ "responseHeader": { "status": 0, "QTime": 32 }, "response": { "numFound": 21, "start": 0, "docs": [ { "description": "A unique wave design sets apart this wedding band, craft ...

Struggling to find a way to showcase API data on a HTML site

Is there a way to dynamically show the live prices of crypto currencies on my website? I wrote a script that successfully displays the current price, but I'm struggling with implementing auto-refresh using setInterval. Here's the code I have so f ...

Unable to use simple json to serialize a Python Appengine GeoModel subclass

Currently, I am developing a straightforward app engine application that leverages the geo-searching proximity_fetch feature. Upon executing the search and applying additional data filtering, everything proceeded smoothly (I verified the number of results ...

How to effectively filter a JSON array using multiple keys?

I need help filtering my JSON data by finding the objects with key 'status' equal to 'p' within the lease array. I attempted to use the following function, but it did not achieve the desired result: myActiveContractItems.filter((myActiv ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

Exploring multilingual options with VeeValidate/i18n in version 4

Previously, I utilized VeeValidate v2 and had a setup like this: VeeValidate.Validator.localize('en', customErrors); const customErrors = { custom: { someField: { required: 'error.required', }, ... }} I have JSON files such ...

The module 'AppModule' is importing an unexpected value 'AppAsideModule'. To resolve this issue, make sure to include an @NgModule annotation

Recently, I attempted to upgrade my Angular project from version 13 to version 17. However, during the process, I encountered an error stating "Unexpected value 'AppAsideModule' imported by the module 'AppModule'. Please add an @NgModul ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

Struggle with Transmitting Information in Ionic 2

I have been working on an Ionic project that involves a JSON file with preloaded data. The initial page displays a list from which a user can select an item to view its content. However, I am encountering a "Response with status: 404 Not Found for URL" err ...

Is there a way to stop SerializeJSON from converting Yes/No/True/False strings into boolean values?

My current issue involves a data structure stored in JSON format after being converted using the serializeJSON function. The challenge I am facing is that certain strings, like 'Yes', 'No', 'True', and 'False' in Col ...

What is the best method for extracting a specific value from this JSON data?

Trying to extract the text value from a JSON response? Wondering how to retrieve the 'text' field, specifically looking for "Киргизия, Бишкек, Чуйский проспект, 213" ?? { "response":{ "GeoObjectCollection" ...

Tips on preventing the occurrence of double encoding in raw JSON output from a view

I am encountering a JavaScript error while attempting to parse JSON data obtained from my controller: Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse () at stores:76 This is the code I use to serialize my list of elem ...

Implementing autocomplete feature with Bootstrap 3

I am currently implementing typeahead.js to create a dynamic search functionality. The goal is to search through a JSON file and display the results on the screen. To achieve this, I have prepared a JSON file that contains all the devices that will be sea ...