Reputation: 17
I'm using unshift to add data to the beginning of an array
x.done(function(data) {
data.unshift({ "data": {
"number": "default",
"description": "Account Default"
} });
});
But it's giving me Uncaught TypeError: data.unshift is not a function
Although, I have used unshift before, and it works fine. I cannot work out what the issue is with this one.
I was also trying to add a second array inside data
but this was returning a different error (I think I got the syntax wrong)
data.unshift({ "data": {
"number": "default",
"description": "Account Default"
},
{
"number": "default",
"description": "Account Default"
} });
Upvotes: 1
Views: 209
Reputation: 1535
var data = [{
"data": {
"number": "default",
"description": "Account Default"
}
}];
data.unshift({
"data": {
"number": "default",
"description": "new Data 1"
}
})
data.unshift({
"data": {
"number": "default",
"description": "new Data 2"
}
});
// 3) [{…}, {…}, {…}] results 3
Upvotes: 1
Reputation: 1
Since unshift
only works with the Array
type, are you certain that data
is in fact of type Array
?
You could for example check this with the Array.isArray()
method:
x.done(function(data) {
console.log(Array.isArray(data));
});
Regarding your second problem it is indeed just a syntax error.
Upvotes: 0
Reputation: 1293
unshift
works only with Array
. But to add data at the beginning of an object
, you can use ES6 spread
syntax:
data = {
{ "data": {
"number": "default",
"description": "Account Default"
}
},
...data
}
Upvotes: 0