I am trying to create an array which will hold just the Name elements from this array:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"}];
I am new to JavaScript and I am not sure how this would be done.
Here is a good read to understand how object works: http://www.w3schools.com/js/js_objects.asp
if you really want the name first element from this array just use
array[0]
If you want an array of just the objects that have a Name key, you can use Array.prototype.filter().
This will return a two-item array [{Name: "steve"}, {Name: "conor"}]:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"},
{Name: "conor"}, {Age: 18}, {Location: "Uk"}];
var names = array.filter(function(obj) {
if ('Name' in obj) {
return true;
} else {
return false;
}
});
If you want an array of just the Name values of just the objects that have a Name key, you can use Array.prototype.filter() and Array.prototype.map() together.
This will return a two-item array ["steve", "conor"]:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"},
{Name: "conor"}, {Age: 18}, {Location: "Uk"}];
var names = array.filter(function(obj) {
if ('Name' in obj) {
return true;
} else {
return false;
}
}).map(function(obj) { return obj['Name']; });
Either way, you may want to take another look at the structure of your array. It probably makes more sense to group your "people" so that each one is a single object, something like:
[{name: "steve", age: 18, location: "Uk"}, {name: "conor", age: 18, location: "Uk"}]
A new feature that javascript has is array destructuring!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
It removes all the complexity of using a custom function, or using the hard coded 0 index (seems like a code smell).
Just destructure the value into a variable. If the array is empty the value will be undefined.
const arr = ["one", "two", "three"];
const [first] = arr;
I know this is an older post but I have a pretty cool solution that gets key from the array and then uses that to return the first item, or alternatively last, the current code is es6 but its simple to convert to es5.
Array.prototype.first = function () { let k = Object.keys( this ); return this[ k[ 0 ] ]; }
//re for last...
Array.prototype.last = function () { let k = Object.keys( this ); return this[ k[ k.length - 1 ] ]; }
To change to es5 use var rather than let.
Reason for this prototype is to make sure that regardless or the index system used will always return first element or the last element...
var first = array[0];To getNamefrom it, usefirst.Name.Nameelements looks badly designed to start with - it looks like it ought to be an array of objects that looks more like:[{Name: "steve", Age: 18, Location: "Uk"}]rather than individual objects for each property.