0

Am trying to converting some strings from json response to number. for example

zipcode: "92998-3874" to 92998-3874. came across this SO. but don't where its getting failed. followed by that i need to loop it in my view but am facing below error in stack blitz console.

ERROR
Error: Cannot find a differ supporting object '[object Object]' of type 'Clementina DuBuque'. NgFor only supports binding to Iterables such as Arrays.
Unable to display error. Open your browser's console to view.

so far:

export class AppComponent {
  name = 'Angular';
  private _userList = [];
  private _userListAddress:any = [];
  _sampleURL = 'https://jsonplaceholder.typicode.com/users';

  constructor(private _http: HttpClient) { }
  _loadData() {
    this._http.get<any[]>(this._sampleURL).subscribe(data => {
      this._userList = data;
      this._userListAddress = data[0].address.suite;
      console.log(this._userList);

      for (var _address in this._userList) {
       this._userListAddress = this._userList[_address];
        console.log('address', 
        parseInt(this._userListAddress.address.zipcode));

        /* 

        //below snippet is used to convert strings to num

        [].forEach.call(this._userList, function (a, b) {          
          [].forEach.call(Object.keys(a), function (c) {            
            if (!isNaN(this._userList[b][c]))             
              this._userList[b][c] = +this._userList[b][c];
          });
        });
        console.log(this._userList); */
      }
    }
    )
  }
}


<button (click)="_loadData()">Load data</button>

<div *ngFor="let list of _userList">
<ul>
<li>{{list.address.zipcode}}</li>
</ul>

<div *ngFor="let addresList of _userListAddress">
    <ul>
<li>{{addresList.address.zipcode}}</li>
</ul>
</div>
</div>

where am doing wrong or suggest better way to achieve this. Helps much appreciated.

Stack Blitz

Mr. Learner
  • 978
  • 2
  • 18
  • 48
  • 1
    Can you produce the link of the stackblitz that you have worked?? – Maniraj Murugan Mar 08 '19 at 07:21
  • @ManirajfromKarur i've updated pls check the link – Mr. Learner Mar 08 '19 at 07:25
  • 1
    1) Why do you want to convert string to number? 2) Do you realise that this would cause the expression and the result will be a subtraction – Sergey Mar 08 '19 at 07:28
  • Is that what you want? https://stackblitz.com/edit/angular-bjs4qh?file=src/app/app.component.html – Sergey Mar 08 '19 at 07:32
  • i've to start some other requirement. for that i need to convert this from string to number then only i can come the conclusion whether the other pending requirement is feasible or not. that's why. i've to implement contentEditable concept in my roadmap – Mr. Learner Mar 08 '19 at 07:33
  • the error say you that you has not an array else an object.e.g. [{prop1:..,prop2:..},{prop1:..,prop2:..}..] is an array {result:[{prop1:..,prop2:..},{prop1:..,prop2:..}..]} is an object, {prop1:..,prop2:..,prop3:..} is an object too – Eliseo Mar 08 '19 at 07:33
  • @worstCoder the idea behind the `contentEditable` is not a number. All the inputs user change are string as well as divs with content – Sergey Mar 08 '19 at 07:34
  • @Sergey i've already achieved that. without any issues. the thing is . want to convert zipcode to number from response. there is requirement is pending followed by that – Mr. Learner Mar 08 '19 at 07:35
  • @worstCoder the easiest way to convert is to use `+` before the string. That will convert automatically string to number – Sergey Mar 08 '19 at 07:36
  • no no.. i know what actually 'contentEditable' is.and you also right. very sorry i cannot expose the requirement here. – Mr. Learner Mar 08 '19 at 07:37
  • `92998-3874` is not a number. If you try to convert it to number, you will get a `NaN` value. –  Mar 08 '19 at 07:37
  • @trichetriche yes its not a num. thats why am looking for to covert into int or number type – Mr. Learner Mar 08 '19 at 08:24
  • My point is that you can't, for several reasons besides the format. For instance, what if the code is `00012-3874` ? Assuming you COULD convert it to number, that would result in a `12-3874` result. I think you should stick to strings and work with that. But again, [explain the original issue you're having, rather than asking for help on what you think is the answer](http://xyproblem.info/) –  Mar 08 '19 at 08:28

1 Answers1

1

If we are talking about that issue :

ERROR
Error: Cannot find a differ supporting object '[object Object]' of type 'Clementina DuBuque'. NgFor only supports binding to Iterables such as Arrays.
Unable to display error. Open your browser's console to view.

It's here :

for (var _address in this._userList) {

_address - is an user-object here like

"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}

and then you are trying to get user-object from the array of users bypassing user-object as a key which is wrong actually. this._userListAddress = this._userList[_address];

So it's not a conversation issue, just check the flow of your code.

Update

Just replace the special character and then parse:

// ES6
let stringNumber = '123456-123';
let convertedNumber = Number(stringNumber.replace('-',''));
console.log(convertedNumber);
// pure js
let anotherStringNumber = '123456-123';
let anotherConvertedNumber = parseInt(anotherStringNumber.replace('-',''));
console.log(anotherConvertedNumber);
un.spike
  • 4,857
  • 2
  • 18
  • 38