Extract JSON content from an array's values containing underscores

I am currently working with an array of objects and need to implement a filter on it. The objects in the list contain an owner_id property within the JSON...

Currently, I am looping through all the items in the array. However, I want to exclude those where the owner_id matches any value in my filterarray:

var filter = "[14657612, 2215375794]";

            $.ajax({
                url: 'myEndPOint',
                dataType: 'json',
                success: function(data) {
                    var media = data.media;
                    var arr = [];

                    _.filter(media, function(val){
                         //The filtering logic should be applied here to exclude items with owner_id that matches any value in the "filter" array
                    });

                    for(i=0; i < media.length; i++) {
                        var thumb = media[i].thumbnail;
                        var html = "<li><img src=" + thumb + " /></li>";
                        arr.push(html);
                    }
                    $(".social-ribbon-target").append(arr);
                    $(".loading").css("display", "none");*/

                },
                error: function(error) {
                    console.log("error");
                }
            });

Answer №1

You mistakenly declared filter as a string, when it should be an array.

Correction:

var filter = "[14657612, 2215375794]";

Change to:

var filter = [14657612, 2215375794];

Answer №2

The enchantment will take place in this very spot

It's not really magic, but rather a function that yields either true or

false> indicating whether the item should be part of the array being returned.</p>

<p>If your filter is currently an array and not a string (if it is a string, you will need to parse it using <code>filter_arr = JSON.parse(filter)
), you can craft your filtering function like so:

var filter = ["one",  "two", "three"];

var media = [{owner_id: "one"}];

console.log(_.filter(media, function(item){
    return filter.indexOf(item.owner_id) >= 0;
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

Every click will nudge the square to the right

I have a square that should move 100px to the right when clicked, but on the next click it moves back to the left. How can I resolve this issue? On JSFiddle, the code works fine. However, when I try to run it in Chrome, I get an error message: Cannot re ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

What is the functionality of the "respond_with_navigational" feature?

Currently, I am integrating Devise and DeviseInvitable to handle authentication in my application. However, I'm facing challenges when trying to incorporate AJAX functionality into InvitationsController#update. The structure of the controller in Devis ...

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

Error encountered: GWT RPCManager performTransactionReply- Transaction does not exist

I am currently utilizing SmartGWT -4.0 and attempted to execute the example of utilizing DataSource with Json, RestDataSourceWithJson.zip. However, upon running it, the development mode console showed me the following error: [ ERROR ] [ restdatasourcewi ...

all-encompassing ajax call method with jquery

Is there a universal function for calling ajax requests globally? For example, instead of writing the same code multiple times: $.ajax({ url: some_url_address, type: 'post', data: $('#form').serialize(), dataType: &apos ...

Increase the worth of current value

Whenever a user enters their name into an input box, I want it to be shown after the word 'hello'. However, currently, the word 'hello' gets replaced by the user's name instead of being displayed after it. var name = document.ge ...

Having trouble finding the element within the form tag even after attempting to use .switchTo().defaultContent()

My HTML is structured like this: <section> <div> <form> <div>Username field</div> <div>Password field</div> <div> <div>.. <div>.. <iframe& ...

Is it possible for ng-change to invoke another controller?

Can someone help me with the following HTML code? <div ng-controller="select"> <select ng-options="n for n in names" ng-model="selected.item" ng-change="change()"> </select> </div> <div ng-co ...

Resolving Issues: AngularJS Service Utilizing GET JSON Data

I've been working on a basic AngularJS project that reads data from an external JSON file. Despite multiple attempts, I'm unable to figure out why the application isn't functioning properly. Any suggestions or insights would be greatly appre ...

Automatically forward to m.example.com on mobile devices using nodejs

Is there a way to create a subdomain in Node.js, such as m.example.com, and have it redirect to m.example.com on mobile devices? I've searched for answers but haven't found a satisfactory solution. One suggestion is to use nginx in front of Node, ...

Converting device log data files into JSON format with Python

I have a task to analyze device logs retrieved from a broadcom source The log text file structure is as follows: bmx-95-ccs019:FID928:admin> fdmishow Local HBA database contains: 10:00:00:30:ma:i1:3g:2e Ports: 1 10:00:00:30:ma:i1:3g:2e Po ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

Generating a new display div element using an anchor link

I've set up a div container with a button that, upon clicking, adds a class to an element in my markup causing it to expand and take over the entire screen. Markup before: <section class="isi" data-trigger="toggle" data-trigger-class="isi--show-i ...

Using Javascript and Node.js, a child class instance in ES5 can access a method belonging to its parent

I am facing an issue while trying to call a parent's method from child's constructor. Below is the code snippet: parentClass.js var ParentClass = function(arg) { this.arg = arg; this.result = {}; }; ParentClass.prototype = { constr ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

Tips for displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

Installing npm modules can be a time-consuming task when running docker-compose

I have been working on a project using Next.js and a PostgreSQL database in a Docker container. The setup of my project involves Docker Compose. However, I've noticed that when I run docker-compose up, the npm install command takes an incredibly long ...

The textgeometry element is not appearing in the three.js scene

I've inserted a boxgeometry into the scene with the intention of adding text to indicate the side of the cube. However, I am encountering difficulties in incorporating textgeometry into the scene. This is my code: const loader = new FontLoader(); loa ...

trouble concerning the responsiveness of a jQuery popup

Hello, I am trying to create a responsive login popup using jQuery but have been struggling for a week. Below is the code snippet that I have been working on. Any help or guidance would be greatly appreciated. //scriptLogin.js archive $(document).ready ...