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?
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?
You can make this in ES6/5
data.map(function(element) {
return element.username;
});
Or without loop
data[0].username
data[1].username
...
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:
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
.
data[0][username];
data[1][username];
data[2][username];