0

I have, what I believe to be, an array of objects:

[{"Id":1,"productId":122,"product_quantity":1}, {"Id":1,"productId":133,"product_quantity":2},{"Id":2,"productId":144,"product_quantity":1}]

I am using this code to get all the values:

$.each(JSON.parse(myArray), function(key, value){ // stuff }

I am trying to filter on Id and return the results associated with it. I have tried nesting .each and using if(value.id = myVariableID) but nothing seems to work.
I would like to return (where Id = 1):

id : 1 | productID : 122 | product_quantity: 1, id : 1 | productID : 133 | procuct_quantity: 2

as an example.

user2796515
  • 264
  • 3
  • 16

1 Answers1

0

Why just don't use Array's filter():

var myArray = [{"Id":1,"productId":122,"product_quantity":1}, {"Id":1,"productId":133,"product_quantity":2},{"Id":2,"productId":144,"product_quantity":1}];

var res = myArray.filter(i => i.Id == 1);
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • when using .filter, I get `.filter is not a function`. – user2796515 Mar 14 '18 at 16:37
  • @user2796515, please follow my code snippet, how I have used filter on the array to get the desired output....thanks. – Mamun Mar 14 '18 at 16:41
  • that does work, but when I insert my actual array as the myVariable.filter it doesn't work. Must be something else I am doing wrong - I have clicked yours as a correct answer and will keep working on it. Thank you. – user2796515 Mar 14 '18 at 16:45
  • @user2796515, you are most welcome and best of luck. – Mamun Mar 14 '18 at 16:47