1

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?

5 Answers 5

3

use the for-of

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

}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

Comments

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

Comments

1

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.

Comments

1

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]);
}

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.