-3

I have the following JSON document,

var data = [
  {"id":1, "username":"user1"},
  {"id":2, "username":"user2"},
  {"id":3, "username":"user3"}
]

How to get all the values with the key "username", without using any loop?

Rob Fox
  • 5,355
  • 7
  • 37
  • 63
Krisalay
  • 235
  • 1
  • 3
  • 12
  • What is your language ? – Gearnode Aug 21 '16 at 08:01
  • @Gearnode: The language is javascript, but i dont want to use any loop – Krisalay Aug 21 '16 at 08:02
  • @Krisalay, Please check the answer . Hope you are looking for the same solution..`values with the key "username", without using any loop`. – Debug Diva Aug 21 '16 at 08:28
  • @RohitJindal yeah your solution works, but this solution is not without using loop, in fact it is using the loop internally – Krisalay Aug 21 '16 at 08:31
  • @RohitJindal got it.Thanks – Krisalay Aug 21 '16 at 08:43
  • Please educate yourself on the meaning of the term "JSON". This is not a JSON object (actually, there is no such thing as a "JSON object"). Also, why do you not want to use a loop, and what do you mean by "using any loop"? Any logic to go through the array and find certain elements will by definition use a loop in one way or another. –  Aug 21 '16 at 10:23
  • The only alternative to using a loop is to use recursion. Is that the kind of solution you were looking for? –  Aug 21 '16 at 10:49
  • Nor is it a "JSON document". Neither I nor any else knows what that means. You must have meant "JavaScript object" or "JavaScript array". –  Aug 21 '16 at 10:50

3 Answers3

1

You can make this in ES6/5

data.map(function(element) {
  return element.username;
});

Documentation here

Or without loop

data[0].username
data[1].username
...
Gearnode
  • 693
  • 7
  • 21
1

Try this it will work:

var data = [
  {"id":1, "username":"user1"},
  {"id":2, "username":"user2"},
  {"id":3, "username":"user3"}
];

var propUsername = data.map(function(elem) {
  return {username:elem.username};
});

console.log(propUsername);

Output:

enter image description here

Working fiddle:

https://jsfiddle.net/kgpumk4r/

Difference between forloop and map:

  • loop iterates over a list and applies some operation with side effects to each list member (such as saving each one to the database for example)

  • map iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (such as get single property from each object)

Hence, We can prefer map over foreach loop as execution will be fast with map.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • What is `forloop`? Also, there is little to no performance difference between `map` and `forEach`. –  Aug 21 '16 at 10:24
0
data[0][username];
data[1][username];
data[2][username];
Partha Mitra
  • 130
  • 7