简体   繁体   中英

How to push JSON records into an empty array as individual elements [Angular]

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.

The problem is you are pushing an array into array. You should push individual 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.

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM