0

I've recently started working on Angular. I'm creating a filter for my Angular application. The scenario is, I've 100(say) users and their personal details in JSON format. I'm using JSONPlaceholder, the fake rest API, for this. I'm using fetch() method to get all the those user records and all those records have to sit in my local array usres=[];. I want this so that later I can display these users on cards and also i would like to apply filter based on name, location, skills, etc. My problem is that I'm not able to push values into my users array. I tried taking help from:

  1. JSON arrays: w3school
  2. How to convert JSON object to JavaScript array?
  3. How to push JSON object in to array using javascript

Here is that entire JSON that I'm talking about.

I'll take care of filtering myself, please help me populate my users=[]; array. From there I can take charge.

Here is the code.

card.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  ...
})
export class CardComponent implements OnInit {

  text='';

  users=[];

  filteredUsers=[];

  constructor() { }

  ngOnInit() {
    fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => this.users.push(json))
  }

  SearchFunction(text) {
    this.filteredUsers=(this.users.filter(e => {
      return e.name.toLocaleLowerCase() === text.toLocaleLowerCase ||
      e.name.toLowerCase().indexOf(text.toLowerCase()) >= 0
    }));
    console.log(this.filteredUsers);
  }
}

But I think this stackblitz will save everyone's time and efforts. Please correct me.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110
  • Please post relevant code (and possibly sample data) here, instead of off-site. Questions should be self-contained and shouldn't require visiting other sites to be answerable. – VLAZ Jan 15 '20 at 10:00
  • Done. I've pasted the relevant code as well. – Tanzeel Jan 15 '20 at 10:03

2 Answers2

1

The problem is you are pushing an array into array. You should pushindividual elements and concat arrays.

It should be either:

this.users = json;

Or:

this.users.concat(json);

Or:

this.users.push(...json); // Destructure the array first

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Also, should probably use Angular HttpClient for fetching data.

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
1

The get requests is returning an array. So you are pushing an array into another array. Either you can set your users list equals to your json result or u can push each element into the array: "this.users.push(...json)"

Loxx
  • 111
  • 9