Reputation: 6217
Using JavaScript how can I remove an object from an array and return that object? For example, change this:
[{first:"John", last:"Smith"}]
...to this:
{first:"John", last:"Smith"}
http://plnkr.co/edit/VqBCsXGuMM54MwHIKW3c?p=preview
Upvotes: 0
Views: 78
Reputation: 16636
You could use the pop() method. It will always remove the last element from array and handle it to you;
Example:
var myArray = [{first:"John", last:"Smith"}]
var myObject = myArray.pop()
Now your myObject
value will be {first:"John", last:"Smith"}
and your myArray
will be empty
If you had more than one items:
var myArray = [{first:"John", last:"Smith"}, {first:"Test", last:"Now"}]
var myObject = myArray.pop()
What happens here is that your myArray will have just the first value and the myObject will have the last one {first:"Test", last:"Now"}
You could also take a look at splice()
Upvotes: 0
Reputation: 48287
Use splice
. It will remove some items from the array and return them.
var data = [{first:"John", last:"Smith"}];
var extract = data.splice(0, 1);
console.log(extract, data); // will print: {first..., last...}, []
Note that splice does return an array itself, so you'll have to take the appropriate elements from that.
If you only have a single element, you can splice
, pop
, or simply take the element by index and then truncate the array.
Upvotes: 4