I'm looking to extract dict values by key, and I've attempted to add those values to an empty array using the concat() function, however it's printing the values but within their own arrays (atleast it appears that way since each value is surrounded by unique sets of brackets).
var dict = {Name: 'Chris', Height: 150, Location: 'New York'};
var dictVal = new Array();
for (var key in dict) {
var val = dict[key];
console.log(dictVal.concat(val));
}
How do I merge the values so they live within their own single set of brackets to denote the list of values within dictVal
?
The mistake that you're making is that Array.concat
returns a new array meaning
dictVal = dictVal.concat(val);
is what you want in order to get the result that you want. Alternatively you can also do
for (var key in dict) {
var val = dict[key];
dictVal.push(val);
console.log(dictVal);
}
if you don't want to generate new arrays.
Moreover, there are better ways to do what you want for example mapping the keys of the object to the values:
var dict = {Name: 'Chris', Height: 150, Location: 'New York'};
var dictVal = Object.keys(dict).map(key => dict[key]);
Iterating through Object.keys
is usually preferable to a for...in
because
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
and Array.map
just saves you several lines of code.
Also as a side note using new Array()
is generally not common. You'd want to do
var dictVal = []
just to be in better accordance with common JS conventions.
You may do as follows in modern browsers;
var dict = {Name: 'Chris', Height: 150, Location: 'New York'},
dictValues = Object.values(dict);
console.log(dictValues);
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