Jasper
Jasper

Reputation: 2231

React - for loop only returns index and not whole object

I have a component which has the following object ('items') in its state:

items:
  count: 2
  next: null
  previous:  null
  results: Array[2]
    0: {…}    
      id: 1
      price: "100.00"
      show_in_shop: true
      tax_percentage: "5.0000000"
      title: 'Object title'
      type: "assessment"

    1: {…}
      id: 2
      price: "1000.00"
      show_in_shop: true
      tax_percentage:"8.0000000"
      title: "Title of this object"
      type: "class"

I am creating a filter that loops over this.state.items.results and checks if the values of the Item object are in the search query.

However, I am running into the following problem, when I run this code:

for (let item in this.state.items.results) {
            console.log(item);

What gets printed to the console is

0
1

And not:

0: {…}    
      id: 1
      price: "100.00"
      show_in_shop: true
      tax_percentage: "5.0000000"
      title: 'Object title'
      type: "assessment"


1: {…}
      id: 2
      price: "1000.00"
      show_in_shop: true
      tax_percentage:"8.0000000"
      title: "Title of this object"
      type: "class"

But why? When I check the state in the react-chrome plugin I see that the 'item.results' is populated with data and contains more data than is being printed to the console. Does anyone know why the loop is only looping over the index and not returning the object?

Upvotes: 1

Views: 837

Answers (5)

Furqan Shaikh
Furqan Shaikh

Reputation: 381

for...in will return index of the collection and not the item of the collection. For eg:

var array = [10,20,30];
for(var item in array){
console.log(array[item]);
}

Upvotes: 1

Fadi Abo Msalam
Fadi Abo Msalam

Reputation: 7197

use the for-of

for (let item of this.state.items.results) {
     console.log(item);

}

Upvotes: 2

Mayank Shukla
Mayank Shukla

Reputation: 104399

for...in will gives the index only, if you want the each object then use for...of.

Like this:

var arr = [{a:1}, {a:2}];

for(let el of arr){
   console.log(el);
}

For the looping you can use #array.forEach or #array.map also, depending upon the requirement.

Upvotes: 1

Rodius
Rodius

Reputation: 2311

this.state.items.result.forEach(item => console.log(item));

Upvotes: 1

TinkerTank
TinkerTank

Reputation: 5805

javascript for .. in indeed only returns the index.

Use:

for (let key in this.state.items.results) {
    let item = this.state.items.results[key];
    console.log(item);
}

Upvotes: 2

Related Questions