Push is not a function ошибка

Мне нужно сформировать из Массива содержащего js-объекты — новый js-объект c объектами, но в итоге получается сформировать только массив с объектами:

Получилось сформировать так:
Array [ Object, Object ]

А нужно чтобы получился объект:
Object { cols: Array[4], rows: Array[1] }

Моя реализация:

var arr = [
	{Rank:1,Country:"Moscow",US$:"101994"},
	{Rank:2,Country:"Luxembourg",US$:"101"},
	{Rank:3,Country:"Monaco",US$:"1019"}
]

var dataCharts = [];
dataCharts.push({ cols: [{id: "year",label: "Год",type: "string"}]});
arr.forEach(function (element, index) {
        dataCharts[0].cols.push( {id: element.Rank,label: element.Country,type: element.US$} );
});


dataCharts.push( { rows:[ { c: [ {v: "2015"} ] } ] } );
arr.forEach(function (element, index) {
        dataCharts[1].rows[0].c.push( {v: "101994", f: "101994"} );
});


console.log(dataCharts);

1) Если изменяю строку «var dataCharts = [];» на «var dataCharts = {};», получаю ошибку «TypeError: dataCharts.push is not a function»

2) Попытался конвертировать таким вот образом:

var obj = {};
dataCharts.forEach(function(element, index){
    obj[index] = element;
});
console.log(obj);

получаю вот такой такой вариант:
Object [Object, Object]

Labrador retriever puppy walking on green grass

Sometimes, we want to fix Uncaught TypeError: data.push is not a function with JavaScript.

In this article, we’ll look at how to fix Uncaught TypeError: data.push is not a function with JavaScript.

How to fix Uncaught TypeError: data.push is not a function with JavaScript?

To fix Uncaught TypeError: data.push is not a function with JavaScript, we should make sure data is an array.

For instance, we write

const data = [
  {
    name: "ananta",
    age: "15",
    country: "Atlanta",
  },
];

data.push({ name: "Tony Montana", age: "99" });
data.push({ country: "IN" });

to declare the data array.

And then we call data.push to append new entries into data.

Conclusion

To fix Uncaught TypeError: data.push is not a function with JavaScript, we should make sure data is an array.

Web developer specializing in React, Vue, and front end development.

View Archive

Answer by Sloane Cummings

if it’s just an object you can use,

19

Because data is not an Array. If it’s an object, just set date.country = ‘IN’. If it’s a «JSON string», you better deserialize it first.

– haim770

Apr 17 ’15 at 10:23

,then
data.push(») will not work as it is not an array anymore.,you can use push method only if the object is an array:

Change data{"name":"ananta","age":"15"} to following:

var data = [
    { 
        "name": "ananta",
        "age": "15",
        "country": "Atlanta"
    }
];

data.push({"name": "Tony Montana", "age": "99"});

data.push({"country": "IN"});

..

Cool stuff to know:

var array = new Array();

is similar to:

var array = [];

Also:

var object = new Object();

is similar to:

var object = {};

You also can combine them:

var objectArray = [{}, {}, {}];

Answer by Ryleigh Hancock

So I’m trying to push new elements to a data object. But I’m receiving errors that push is not a function,Uncaught TypeError: this.question[i].push is not a function,Looks like question[i] is an Object and not an Array.,I actually want to run this emitietly when the “page” has loaded, but I have to put this function in methods, and then call the function from created()

I actually want to run this emitietly when the “page” has loaded, but I have to put this function in methods, and then call the function from created()

        addToArray: function(){
            for(var i = 0; i < this.question.length; i++){
                this.question[i].push({test: 'Yeey it works!'})
                for(var j = 0; j < this.question[i].choice_in_random_order.length; j++){
                    this.question[i].choice_in_random_order[j].push({is_click: false})
                    this.question[i].choice_in_random_order[j].push({is_danger: false})
                }
            }  
        },

Answer by Khari McKee

It outputs the json values when it has been clicked on.,Error message: Uncaught TypeError: favorites.push is not a function,#2) The following is your addFavorite function:,Found the answer I picked up the wrong variable (norrisJoke), but that should be variable favorites in this context.

When I click on a checkbox it will pass an id and text, but looking at the localStorage I see [object object]. I know the typeof storage is object and should be an array. The question from my side is, how should I turn an object into an array?

	function addFavorite(jokeId, jokeText) {
		let storage = localStorage.getItem('favoList') || [];
		let norrisJoke = {
			id: jokeId,
			joke: jokeText
		};
		console.log(norrisJoke);
		storage.push(norrisJoke);
		console.log(typeof storage);
		localStorage.setItem('favoLis', norrisJoke);
    }

Answer by Elianna Beasley

Search Answer Titles

let test = {
		name: 'NN',
  		email: '[email protected]'
};

test.phone = '234654234';

// result { "name": "NN", "email": "[email protected]", "phone": "234654234" }

Answer by Gatlin Houston

I spent a lot of time looking at it and I don’t see anything wrong, but the Erro message says otherwise.,Also, I know that there is a better way to accomplish the task, but I just can’t wrap my head around the Error message and what’s causing it.,In my code, I am trying to add the space string to the end of the string I enter as an argument to the pad function. The amount of times the space gets added is determined by the value contained in the num argument.,You used the + operator to add space to the array final and assigned it back to final instead of using .push() so it’s no longer an array. What JavaScript is actually doing is using the array’s .toString() method then concatenating the space string, then assigning the result of that back to final.

In my code, I am trying to add the space string to the end of the string I enter as an argument to the pad function. The amount of times the space gets added is determined by the value contained in the num argument.

const pad = (string, num) => {
    let final = [string]; // supposed to be an array
    let space = '-';

    for (let i = 0; i < num; i++) {
      if (i === 0 && num % 2){
        final = final + space;
        num--;
      }
      final.push(space); // TypeError: final.push is not a function
    }
    return final.join('');
  };
  
  console.log(pad('Hi', 3));

Answer by Musa Lynch

when I try to run this code I face this issue «TypeError: undefined is not a function
«,Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

,Treehouse for Libraries,© 2021 Treehouse Island, Inc.

var names = ['math','john']; 
names.push('alice');

Answer by Edison Pope

The push method appends values to an array.,Merging two arrays can also be done with the concat() method.,
The push() method adds one or more elements to the end of
an array and returns the new length of the array.
,
The new length property of the object upon which the
method was called.

push(element0)
push(element0, element1)
push(element0, element1, ... , elementN)

Answer by Haley Quinn

«Uncaught TypeError: visitorIDs.push is not a function». ,

SharePoint Meta

,But above code will help you to resolve your Uncaught TypeError. ,

SharePoint

help
chat

First of all you need to declare an array at the start of your code/function like:

var visitorIDs = [];

Then in setTimeout function you can use it like below:

visitorIDs.push(ResolvedToUser.Id);

So, you need to remove below line from your code which is not necessary:

visitorIDs = ResolvedToUser.Id;

Views: 10

if you call push() method on a variable that is not an array then it throws an error “push is not a function”, To resolve the error, convert the value into an array before calling the method or make sure to only call the push() method on valid arrays.

Example

const myarray = {name: 'askavy'};

//  Uncaught TypeError: arr.push is not a function
myarray.push({name: 'Mark'});

We called the Array.push method on an object, which caused the error.

const myarray  = [{name: 'askavy'}];

myarray.push({name: 'Mark'});

//  [{name: 'askavy'}, {name: 'Mark'}]
console.log(myarray);

Example that checks if the value is an array before calling the push method.

const myarr = null;

if (Array.isArray(myarr)) {
  myarr.push('example');
}

Here we check the variable using isArray method if the value is an array before calling the push method.

If you’re working with an object, that has a specific property that stores an array

Example

const myobj = {
  myarr: [1, 2],
};

myobj.myarr.push(3);

// {myarr: [1, 2, 3]}
console.log(myobj);

Понравилась статья? Поделить с друзьями:
  • Purge unit error ошибка устройства прочистки
  • Punto switcher ошибка windows 10
  • Punto switcher код ошибки 2502
  • Pump low flow intex ошибка 90 бассейн
  • Pull milk frother bosch ошибка