-3

const data = { user: [ { name: 'jack' } ] }

How do I get only Jack when I call the constant.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
D.js
  • 13
  • 1

1 Answers1

0

It is saved as an array. To use its components, you must do the following:

data.user[0].name;
data.user[1].name;
data.user[1].age;

If you want foreach loop in JS you can do like this : @EDIT 1 updated without this

const data = [{name:"Jack", age:"50"},{name:"Brook", age:"20"},{name:"Noob", age:"34"}];
for(const n of data) {
   console.log(n.name)
    console.log(n.age)
}

@EDIT2

const data =  {user : [{name:"Jack", age:"50"},{name:"Brook", age:"20"},{name:"Noob", age:"34"}]};
for(const n of data.user) {
    console.log(n.name)
    console.log(n.age)
}
Adamszsz
  • 561
  • 3
  • 13
  • It works but I have another name also like ```const data = { user: [ { name: 'jack' }, {name: 'brook', age: 20 ] }``` how do I get both names – D.js Jul 29 '21 at 09:09
  • Edited , check it. And approve answear if works :) – Adamszsz Jul 29 '21 at 09:12
  • I have like more than 100 users and name so I can't use this method – D.js Jul 29 '21 at 09:14
  • Edited answear , check it and approve if works :) It will do the same wthing for each user. – Adamszsz Jul 29 '21 at 10:00
  • I'm getting an error ```UnhandledPromiseRejectionWarning: TypeError: this.data is not iterable``` – D.js Jul 29 '21 at 10:43
  • OK , sorry my bad - there you need to delete this before data. Updated again JS file , check now – Adamszsz Jul 29 '21 at 10:50
  • sorry about this but, I have user inside const, which I can't remove so I have to find a way using user inside const data like ```const data ={user[{name:"Jack", age:"50"},{name:"Brook", age:"20"}]}``` – D.js Jul 29 '21 at 10:59
  • added @EDIT2 check now. – Adamszsz Jul 29 '21 at 11:02