0

I want to slice the the json array in Angular which looks like this below.enter image description here

And the code is below

export class AppComponent {
  color: string = 'green';
  public stocklist = [];
  public objectKeys = Object.keys;
  constructor() {
    let url = 'http://localhost:8080/stocks';
    axios.get(url).then(res =>{
      this.stocklist = res.data.result[0].slice(0,10);
      console.log(this.stocklist);
    })
  }
}

But it always shows res.data.result[0].slice is not a function, but we can see res.data.result[0] is literally a json array which can iterate in using *ngFor.

So which shold i use for slicing the json arry.

6
  • 4
    They are objects with integers as key. Not arrays Commented Nov 16, 2020 at 15:40
  • so how could i turn into array Commented Nov 16, 2020 at 15:43
  • 2
    Please dont use axios in angular, change to httpClient Commented Nov 16, 2020 at 15:43
  • 1
    Object.values() or Object.entries() should do the trick Commented Nov 16, 2020 at 15:46
  • @OwenKelvin I used it in Vue, so I thought it gone works too in angular, however i will check the angular doc later about httpclient thanks for your advice. Commented Nov 16, 2020 at 15:57

2 Answers 2

2

slice() is the method of the Array, but you are calling it for the object.

Use Object.values() to make it to array.

export class AppComponent {
  color: string = 'green';
  public stocklist = [];
  public objectKeys = Object.keys;
  constructor() {
    let url = 'http://localhost:8080/stocks';
    axios.get(url).then(res =>{
      this.stocklist = Object.values(res.data.result[0]).slice(0,10);
      console.log(this.stocklist);
    })
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

An addition to @WilliamWang solution implementing Observables

export class AppComponent implements OnInit {
  color: string = 'green';
  public stocklist = [];
  public objectKeys = Object.keys;
  constructor(private httpClient: HttpClient) { }
  ngOnInit() {
    let url = 'http://localhost:8080/stocks';
    this.httpClient.get(url).subscribe(res => {
      this.stocklist = Object.values(res.data.result[0]).slice(0,10);
      console.log(this.stocklist);
    })
  }
}

1 Comment

Thanks for your addition, I just learned to use httpclient instead of axios to execute http request. And at first, I wrote just like you did but it alerted that there were not exist ''data'' attribute for 'res', so in considering the data structure of the val stored in Observable, I had to identify the Observable with an interface so that I could get access to the data inside the observable object.

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.