1

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"
} });
5
  • You are sure that data is an array? Commented Feb 12, 2021 at 8:55
  • below it, I use for(var i in data) {to loop through. it's JSON data Commented Feb 12, 2021 at 8:56
  • unshift is only functional with array Commented Feb 12, 2021 at 8:57
  • It means you are trying to use unshift with an object? Commented Feb 12, 2021 at 8:57
  • Oh, I've just seen it's not returning the same format. It looks like this 01234: {data: {…}, seq: "4", customer: "1234", display: "Number 01234", number: "01234", …} so data is inside another key Commented Feb 12, 2021 at 9:00

3 Answers 3

1
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 
Sign up to request clarification or add additional context in comments.

Comments

0

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
      }

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.