Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first object from array

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.

like image 630
Conor Shannon Avatar asked Jul 16 '26 13:07

Conor Shannon


2 Answers

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]
like image 123
tlebrize Avatar answered Jul 19 '26 04:07

tlebrize


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"}]
like image 39
twernt Avatar answered Jul 19 '26 02:07

twernt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!