Getting a particular attribute and adding it to a collection in backbone.js: The solution explained

With the given JSON structure, I am looking to extract a specific attribute and store it in a collection. The data is formatted as follows:

{
   foo: "lorem ipsum",
   bars: [{
       a: "a",
       b: {c: "d", e: "f"}
   }, {
       a: "u",
       b: {w: "x", y: "x"}
   }]
}

I know how to extract only bars (excluding foo bars) with the help of parse, but my goal now is to retrieve bars, locate a specific object based on the a attribute, and then store b inside a collection.

The approach I have in mind involves:

MyCollection = Backbone.Collection.extend({
    model: MyModel,
    url: "someUrl",

    parse: function(data) {
         data.bars.each(function(bar) {
             if (bar.a == i) {
                 return bar.b;
             }
         }
    }
};

var myCollection = new MyCollection();
myCollection.fetch({
     success: function() {
          console.log("Successfully collected the correct 'b' values!");
     }
});

My challenge lies in determining where and how to input the value of i for the condition if(bar.a == i).

Answer №1

When using the fetch function, any options passed are also forwarded to the Collection.parse method. This allows for customization, as shown in this example:

MyCollection = Backbone.Collection.extend({
    model: MyModel,
    url: "someUrl",

    parse: function(data, opts) {
        console.log(opts);

        // Custom filter logic
        var matches = _.where(data.bars, {a: opts.i});
        return _.map(matches, "b");
    }
});

var myCollection = new MyCollection();

// Specify a filter option when fetching the collection
myCollection.fetch({
    i: "u", 
    success: function() {
        console.log("Filtered collection retrieved successfully!");
    }
}).then(function() {
    console.log(myCollection.toJSON());        
});

You can view a demo of this code in action here.

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

Leveraging React Hooks for managing the Data Provider and Data Context functionality

Currently, I am revamping my DataProvider by upgrading it from a class component to a functional component utilizing React Hooks. I suspect that the issue lies in how I am setting up my context consumer, but I am struggling to find an effective way to tes ...

The primeVue menubar's active/focused item highlighting feature is not functioning correctly

Currently, we are in the process of developing an electron-based application with the front end primarily coded using Vue.js and primeVue. As a novice, I am encountering issues with the menubar component from primeVue. The problem is that no matter which i ...

Ways to determine the total number of pages in a PDF using a stream

Utilizing a library such as pdf-parse enables us to extract the number of pages (numpages) from a PDF buffer. The challenge I am facing is handling large buffers that cannot be stored in memory, prompting me to consider streaming it instead: const response ...

Display the text field in Angular with the appearance of a password field, not an input field

I am currently working with Angular 8 for my Angular-Electron project. Within this application, I have a sensitive field labeled API-Key stored in tabular format that needs to be displayed on the user's account page. However, it must appear as a passw ...

Turn off the feature that highlights links

Hi there! I'm curious to know if it's feasible to remove the highlighting effect when clicking on a link. I'd like the link to function more like an image, without the appearance of a highlighting box upon clicking. ...

React:error:unexpected punctuation

I encountered an issue with this code within the render() function, specifically on the line where I am returning a value and it shows an unexpected token error. Here's the snippet of the code. class PuzzleGame extends React.Component { construct ...

Techniques for transferring information to Highchart directly from session storage

I am attempting to populate a pie highchart with data from a session storage variable, but I am not seeing any results. Here is the desired code: $(function () { Highcharts.chart('container', { chart: { type: 'pie', ...

How to fill an HTML template using ngFor without using a JSON array

Is there a way to fill the HTML with basic JSON like below: { "id": 34, "name": "Tip 33", "description": "Tip description 33", "created_at": "2018-01-26 18:59:19", "updated_at": "2018-01-26 18:59:19" } The code i tried using was: < ...

When two zeros are adjacent, the test fails - Leetcode problem 283: Moving Zeroes

I encountered an issue while working on the leetcode 283 move zeroes problem where I faced a strange test failure when there are two zeros next to each other. Here is the code snippet I used: /** * @param {number[]} nums * @return {void} Do not return ...

Exploring the versatility of ModelMapper: Implementing various typemaps for a single entity

I am currently using ModelMapper for transforming entities into DTOs. However, we have a requirement where the same endpoints will be accessed by multiple consumers. As a result, we need to restrict certain fields based on the consumer. For example: Consu ...

Export the model group to GLB format and then import it into threejs. Can individual materials be added to the models within the model group afterwards?

Let's say I exported a model group named C, which includes two models: A and B. When exporting a GLB file using Blender, does the file contain labels for models A and B? Also, what code should be used to access model A within model group C and apply a ...

"To toggle between VueJS input checkbox and class change, users may need to click the element

I decided to create a list of items with checkboxes. The goal was to tick the checkbox and add a class to the div upon clicking it. Unfortunately, when I click on the checkbox, it only ticks the checkbox itself. I actually need to click it again for the c ...

Troubleshooting problem with binding and calling jQuery javascript functions

I created a custom JavaScript function called 'mc_change' and I want it to be triggered when a textbox's value changes. <input type="text" id="mc_val" onchange="javascript:mc_change();" /> Unfortunately, the function is not working ...

In order to effectively utilize and display images on a webpage, I require a JavaScript array to store image links for use as image sources

I need assistance with changing these images. I am trying to store their links in an array, but when I click the button to change the image, it does not recognize that the array variable points to an image. Can someone offer guidance? Here is my current ...

Using Laravel's AssertJsonCount to count elements in a nested array in Laravel

Is there a way to utilize a nested array index while calling assertJsonCount? After receiving the JSON response below in my test: [[{"sku":"P09250"},{"sku":"P03293"}]] I encountered an error when attempting to apply assertJsonCount: $response->asser ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

AngularJS is patiently awaiting the completion of the translation rendering process

I implemented the ngCloak directive to my body element on the page and every angular-related element, but it appears that it is not working with AngularJS translate. The translate variables show up on the page initially and then get translated after a se ...

Automate brush control and transmit pertinent data through coding

Extending on the query from yesterday's thread, I am working towards implementing multiple brushes. While my current brute force method is functional, I require additional functionality to programmatically manage each of these newly created brushes. ...

Using Angular 6 to load external HTML files with CSS inside a router-outlet

I'm currently working on creating a json-based dynamic template using Angular 6. There are certain scenarios where I need to fetch external html content (which could be stored in a database) along with its corresponding css (also stored separately in ...