Push string to object javascript

var myeleArr = {
                    advertiser :{},
                    campaign :{},
                    strategy :{},
            };

i want to insert some string into myeleArr.campaign object, so i am doing as shown below, but console displays as Object # has no method 'push'

myeleArr.campaign.push(''+myele['name']+'');

Can some body help me.

asked Oct 9, 2012 at 16:39

Push string to object javascript

If you intend for campaign to be a string, then set

myeleArr.campaign = "my string";

If you intend for campaign to hold a bunch of strings, in order, where the strings aren't referred to by name, then make it an array:

myeleArr.campaign = [];
myeleArr.campaign.push("My String");
myeleArr.campaign[0]; // "My String"

If you intend for campaign to hold a bunch of strings by name, then give your current campaign object named properties, and set each of those named properties to be a string:

myeleArr.campaign = {
    title : "My Title",
    type  : "Campaign Type",
    description : "Campaign Description",
    num_managers : 7,
    isActive : true
};

myeleArr.campaign.title; // "My Title"

answered Oct 9, 2012 at 16:48

NorguardNorguard

25.7k5 gold badges39 silver badges48 bronze badges

The push function is used to add an item to an array but campain isn't defined as an array.

Try with this :

 var myeleArr = {
        advertiser :{},
        campaign :[], // this makes an array
        strategy :{},
 };

Or, if you want to have only one value in campaign, don't use push but simply

myeleArr.campaign = '

answered Oct 9, 2012 at 16:40

Denys SéguretDenys Séguret

361k84 gold badges764 silver badges734 bronze badges

The push method is meant for javascript arrays. So, instead of object literals, if you change campaign, etc keys to point to array literals, you'd be able to push. i.e. -

var myFoo = { advertiser: [], campaign: [], strategy: [] };
myFoo.campaign.push('my stuff');

Also, if you just want to assign a string to campaign, you could simply -

var myeleArr = {};
myeleArr.campaign = "...";

Checkout the javascript console in developer tools under Google Chrome, or install nodejs, both are good places to try out these things when you're not sure.

answered Oct 9, 2012 at 16:42

Abhishek MishraAbhishek Mishra

5,0048 gold badges36 silver badges38 bronze badges

Make the campaign as an array instead of an object . Because push is a method on arrays and not objects

campaign :[],

answered Oct 9, 2012 at 16:52

Sushanth --Sushanth --

54.8k8 gold badges66 silver badges102 bronze badges

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Try it

Syntax

push(element0)
push(element0, element1)
push(element0, element1, /* … ,*/ elementN)

Parameters

elementN

The element(s) to add to the end of the array.

Return value

The new length property of the object upon which the method was called.

Description

The push() method appends values to an array.

Array.prototype.unshift() has similar behavior to push(), but applied to the start of an array.

The push() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* ... ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat().

Array.prototype.push() is intentionally generic. This method can be called on objects resembling arrays. The push method relies on a length property to determine where to start inserting the given values. If the length property cannot be converted into a number, the index used is 0. This includes the possibility of length being nonexistent, in which case length will also be created.

Although strings are native Array-like objects, they are not suitable in applications of this method, as strings are immutable.

Examples

Adding elements to an array

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

const sports = ['soccer', 'baseball'];
const total = sports.push('football', 'swimming');

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4

Merging two arrays

This example uses spread syntax to push all elements from a second array into the first one.

const vegetables = ['parsnip', 'potato'];
const moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Merging two arrays can also be done with the concat() method.

Using an object in an array-like fashion

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

const obj = {
  length: 0,

  addElem(elem) {
    // obj.length is automatically incremented
    // every time an element is added.
    [].push.call(this, elem);
  },
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2

Note that although obj is not an array, the method push successfully incremented obj's length property just like if we were dealing with an actual array.

Specifications

Specification
ECMAScript Language Specification
# sec-array.prototype.push

Browser compatibility

BCD tables only load in the browser

See also

How do you push a string in JavaScript?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

Can I use push in object JavaScript?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.

Can push () be used on string?

Pushing on a string is a figure of speech for influence that is more effective in moving things in one direction rather than another—you can pull, but not push.

How do you add a string to an object?

There are two ways to create a String object:.
By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”;.
By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”);.