1

I have a JSON array:

data = [{"user_id":22},{"user_id":12}];

1) I need to find the index of an element. I use the method:

     var value = 22;
     var index = -1;
     var res = this.data.find(function(item, i){
      if(item.user_id === val){
      index = i;
      return i;
      }
     });
     console.log(index, res);

But the problem is that I got index 0 all the time.

2) I need to use the same array in the format:

"test" :{
        "users":[{"user_id":22},
                 {"user_id":12}
                ]
      }

when I use this format:

"test":{
        "users":this.data
        }

but it gives Array(0).

I didn't find anything wrong. Help will be appreciated.

1
  • This should be a javascript question not angular Commented Aug 30, 2018 at 4:42

2 Answers 2

1

use findIndex for this

data = [{"user_id":22},{"user_id":12}];

let indx =data.findIndex(item=>item.user_id == 12);
Sign up to request clarification or add additional context in comments.

Comments

1

Use findIndex method

var indexNum =[{"user_id":22},{"user_id":12}].findIndex((element)=> {
  return (element.user_id == 22);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.