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"}
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"}
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.
.splice
is returning an array with an object (not just an object). Am I missing something? Compare to myObject
: plnkr.co/edit/Pg3rLv2Lspj118i34EBa?p=preview
splice
will remove the elements from the original array and return a new array, which you have to take the element from normally (data.splice(0, 1)[0]
or the like). It does the important step of removing, especially since it can remove element(s) from the middle of another array efficiently.
undefined
when I try .pop()
: plnkr.co/edit/Pg3rLv2Lspj118i34EBa?p=preview
data.splice(0, 1).pop()
or data.splice(0, 1)[0]
or any number of other methods. There is no built-in method (that I know of) to splice a single element out of an array and return it as an object, probably because that behavior wouldn't make sense for multiple elements.
data.splice(0, 1).pop();
and data.splice(0, 1)[0]
both return undefined
plnkr.co/edit/Pg3rLv2Lspj118i34EBa?p=preview
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()