Here is a sample of my data structure in JavaScript:
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
How can I add each "username" to a new array (var result = []
)?
A sample of the final data structure would be:
var result = ["admin1", "admin2", "admin3", "admin4", "admin5"];
Thank you *
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.
A Dictionary object contains a set of key-item pairs. A dictionary's item is a value that is unambiguously associated with a unique key and the key is used to retrieve the item. The key can be of any type except a variant or an array (but generally it is a string or still an integer).
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
Use Array#map
method to generate an array by iterating over the elements.
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
var res = list.map(function(o) {
return o.username
});
console.log(res);
With ES6 arrow function:
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
let res = list.map(o => o.username);
console.log(res);
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"},
{"username":"admin4"}, {"username":"admin5"}];
var array=[];
for (var key in list) {
let value = list[key];
console.log(value.username);
array.push(value.username);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With