Locate a specific element within an array and retrieve its corresponding index

Need help updating a boolean property for all objects in an array with the same user ID. I've outlined my MVC framework below in a concise manner.

Model:

 var posts = [{id:1, user_id:1, is_following:true},
    {id:2, user_id:1, is_cool:true},
    {id:2, user_id:2, is_cool:false}];

View:

<div class="list" ng-repeat="post in posts">
 <button ng-click="unCool(post.user_id,$index)"  ng-if="post.is_cool === true">
 Cool
 </button>
 <button ng-click="makeCool(post.user_id,$index)" ng-if="post.is_cool === false" >
 not Cool
 </button>
 <p>{{post.id}}</p>
</div>

Controller:

$scope.makeCool =function(userid, index){
  //this is an ajax request for brevity i excluded the service 
  coolService.makeCool(user_id)
        .success(function (data) {
             $scope.posts[index].is_following = true;
   //How to locate and update other indexes with the same user ID
          }).
        error(function(error, status) {         
          //do something        
      });
}

$scope.unCool =function(userid, index){
  //this is an ajax request for brevity i excluded the service 
  coolService.unCool(user_id)
        .success(function (data) {
             $scope.posts[index].is_following = false;
   //How to find and toggle other indexes with the same user ID
          }).
        error(function(error, status) {         
          //do something        
      });
}

Answer №1

Avoid the need for Angular, jQuery, or lo-dash functions in this scenario by utilizing the built-in Array.prototype.filter method to streamline the array to only include matching elements and the inherent Array.prototype.forEach method to update each corresponding element.

$scope.posts
  .filter(function(post) {
    return post.user_id === userID;
  }).forEach(function(post) {
    post.is_following = true;
  });

Answer №2

To tackle this issue, one possible method is to leverage the angular filter feature. It's advisable to avoid using $index (and also consider avoiding it in case you plan on filtering your `ng-repeat).

$scope.makeCool =function(userid){
  coolService.makeCool(userid)
        .success(function (data) {
             var posts_to_update = $filter('filter')($scope.posts, function(post) {
               return post.user_id == user_id;
             });
             // Proceed to iterate through and update the boolean property
             angular.forEach(posts_to_update, function(post) {
               post.is_following = true;
             })
          }).
        error(function(error, status) {         
          //handle errors        
      });
}

A similar approach can be applied for handling unCool actions.

Answer №3

To achieve this task effortlessly, utilize the lodash library. Begin by grouping your data based on the "user_id" property. Next, iterate through each group and set a boolean value in the designated property. This way, the boolean property will be correctly assigned for each "user_id".

Answer №4

There seems to be an inconsistency in the object structure within the posts. It appears that the object with the property is_following should not be updated, and instead receive a new property called is_cool.

Whatever logic is being applied seems to be specific to pure JavaScript. To illustrate this, here is an example involving a function called makeCool:

 coolService.makeCool(user_id)
    .success(function (data) {
         $scope.posts[index].is_following = true;
         $scope.posts.map(function(post){//iterate all posts
                if(post.user_id === user_id && post.hasOwnProperty('is_cool')){//and for those that belong to same user and already have property is_cool
                        post.is_cool = true;//set coolness
                }
          });
      }).

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

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

Is it possible to bring in a `devDependency` into your code?

The Mobx DevTool's README instructs users to install it as a dev dependency, and then import it into their code. This approach raises concerns for me because devDependencies are typically reserved for tools used in the build process or managing end co ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

Want to know how to center the value of a slider range input in your React project using NextJS and Tailwind

Can someone help me with the issue I'm having with the offset? Is there a way to link a value to the thumb? I've tried two methods, but one gives a significant offset and the other gives less. However, it seems more like a workaround than a solu ...

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

After removing an element from an array in Vue.js, how can we adjust its class to reflect the change?

Apologies for my lack of proficiency in English. I am eager to find a solution to resolve these issues. I am working on a todolist and encountering an issue where the class ('centerLine') continues to affect the next element after deleting an a ...

A straightforward Node.js function utilizing the `this` keyword

When running the code below in a Chrome window function test(){ console.log("function is " + this.test); } test(); The function test is added to the window object and displays as function is function test(){ console.log("function is " + this.tes ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Share content on Facebook using a single-page application

This inquiry may not be specifically tied to a particular software stack, framework, or coding language. In the current project I'm working on, we are utilizing AngularJS for developing the front-end with a static landing page that loads real data an ...

Guide to creating a contenteditable div that automatically generates smart quotes instead of traditional dumb quotes

I've observed that when I write in Google Docs, I get smart quotes. However, when I create contenteditable divs on my own, I only see dumb quotes. Is there a way to make my contenteditable divs display smart quotes instead of dumb quotes? ...

Is it achievable to have a background image cover size with a responsive rollover effect?

I’m currently facing a unique challenge where I want to have an image as the background of my website, with the size set to cover the entire screen. On this background image, there are elements like buildings that I want to interact with when hovered ove ...

Converting a React.Component into a pure function: A step-by-step guide

Eslint is recommending that I use a pure function instead of a react component. 

I have eslint set up with the airbnb config.

 Error: Component should be written as a pure function - react/prefer-stateless-function class App extends Component ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

Guide to storing a variable value when a user clicks on the client-side in a Grid View:

How can I store data in a variable on client click within a grid view? I have a Stored Procedure that returns Service Id based on the Department code provided. We are binding these details to a Grid View. How can we bind the Service Id to a variable that ...

Why is it that using "return false" does not stop the page from reloading when clicked?

I've attempted using this code, but it doesn't seem to prevent the page from reloading when the onclick function is triggered. What am I missing here? Could this be a problem related to browser compatibility? function track_specs() { $('b ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

My app is having trouble updating routes correctly. Can anyone provide guidance on how to configure routeConfig properly for my application?

I'm facing an issue with my angular 2 typescript app component routes not working properly. Whenever I try to change the route to login in the address bar, it fails to load the corresponding HTML content. Strangely, there are no console errors displa ...

What is the best pattern to utilize for these types of tasks?

I've been struggling a bit with understanding the MVC principle, but I always believed that business logic should be contained within models - please correct me if I'm mistaken. In my current project, I am following the MVC pattern. The rou ...

Unable to view images that have been uploaded through express.js

In my current project with a REST Api, I have been facing an issue while uploading images. The folder structure of the project can be seen here: Under the public folder, there is a subfolder named images where all the image uploads are stored. However, w ...