4

I have an array containing three columns like this:

data.push({
  country: new Date(),
    newSales: Math.random() * 1000,
     expenses: Math.random() * 5000
 });

Now, on button click, I want to add a new column in it. Can anyone let me know how we can do it?

1
  • 1
    If you want to add a new attribute in the first element of data try data[0].newcolumnname = 'whatever value' Commented Jan 29, 2015 at 7:08

5 Answers 5

9

You could iterate though the data array and add key & value to each element.

data[0]["foo"] = bar; // this can be useful if the key is not constant

or

data[0].foo = "bar"
Sign up to request clarification or add additional context in comments.

Comments

1

You could define the columns in your array in a separate object like this:

var cols = { country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 };

Then say, data.push(cols);

Now in your button logic, add a new column (or rather property) to the object as follows:

obj.newCol = 'some value';

This will then be automatically reflected in your array

Comments

1

// Pseudocode

for i in data
    data[i].foo = "bar"

Comments

0

This my way to add column to 2 dimensional array.

I shared for whom concerned.

var textarray = [[{ text: 'Content 1' }, { text: 'Content 2' }], 
                 [{ text: 'Content 3' }, { text: 'Content 4' }]];

Method to add column to array in the right as

insertColumnAtRight() {
    for (var i = 0; i < this.textarray.length; i++) {
      this.textarray[i].push({ text: "" });
    }
}

If you want to add column in the left, you can use unshift method instead of push.

Comments

-1

Please check the "push"-method: http://www.w3schools.com/jsref/jsref_push.asp

1 Comment

If you see my code, I am already using push method to insert item. My question is how to add a new column in the array. not new item. Hope its clear now.

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.