Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Dictionaries Keys Values to Array [JavaScript]

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 *

like image 361
Julia Avatar asked Jun 13 '17 10:06

Julia


People also ask

How do you add a key-value pair to an array?

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.

Can a dictionary key be an 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).

How do you add multiple key-value pairs to a dictionary?

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.


2 Answers

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);
like image 148
Pranav C Balan Avatar answered Nov 04 '22 16:11

Pranav C Balan


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>
like image 38
lalithkumar Avatar answered Nov 04 '22 15:11

lalithkumar