0

I would like to retrieve a speicific array element from a returned JSON request. So far I can get the whole feed, but I am struggling how to restrict it to a specific element.

So far I have this in my service controller;

getJsonData(){
    return this.http.get('https://www.reddit.com/r/worldnews/.json').map(res => res.json());
}

In my page I have;

getdata() { 
    this.HttpModule.getJsonData().subscribe(
      result => {
        this.News= result.data.children(1);
        console.log("success:"+this.News);
      },
      err => {
        console.error("Error : "+err);
      },  
      () => {
        console.log("getData completed");
      }
    );
    }

It should be children by I tried children(1) as a guess but it didn't work

1
  • Did you try parsing your result to object with JSON.Parse and then accessing children[1]? Commented Jul 11, 2017 at 11:39

2 Answers 2

1

The children property is an array, and in javascript to access array items you use [] (the bracket notation).

So use

this.News= result.data.children[1];

Also note that arrays in javascript are zero-based so the [1] will return the 2nd element

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

3 Comments

This is the first thing I tried, unfortunatly this does not work: TypeError: result.data.children is not a function
@RedCrusador just to make sure, you used square brackets [] and not parenthesis () and you still got the error about not a function ?
Yes thats what I got back, they are [ ]
0

Assuming result.data is array . we can do

for ( let item of result.data)
{
   console.log(item.field1);
   console.log(item.field2);

}

1 Comment

Yes say if I want the 1000 th element does that mean I have to iterate through the 999 items to get there?

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.