How to add properties dynamically to each object in an javascript array

12,628

The order of properties in a Javascript object doesn't matter, they aren't strictly ordered.
Given

var cars = [
  {car: "Mercedes A 160", year: 2006, available: true, comesInBlack: 'yes'},
  {car: "Citroen C4 Coupe", year: 2008, available: false, comesInBlack: 'yes'},
  {car: "Audi A4 Avant", year: 2011, available: true, comesInBlack: 'no'},
  {car: "Opel Astra", year: 2004, available: false, comesInBlack: 'yes'},
  {car: "BMW 320i Coupe", year: 2011, available: false, comesInBlack: 'no'}
];

You can simply do the following if you don't have the property ready to send from the backend or want to do it in the frontend for other reasons (smaller payload size etc).

for (i in cars) {
  cars[i].checkbox = false;
}

Now, coming back to the issue of Handsontable column order (which is actually the main problem of the question), you can define it as follows:

var hot = new Handsontable(container,{
  data: cars,
  /* Other config */
  columns: [
    {data: "checkbox", type: 'checkbox'},
    {data: "car", type: 'text'}
    /*Other columns*/
  ]
});

See the manual for further info.

Share:
12,628
user1592380
Author by

user1592380

Updated on June 04, 2022

Comments

  • user1592380
    user1592380 almost 2 years

    I am trying to loop through an array of objects to prepend a property and value to each object . The order of the tables is important because I am trying to use a handsontable view as a client to retrieve the contents of a server side mysql table. I want the handsontable view to have the same column order as the table , but I want to insert a checkbox column as the first column to allow record selection. I have a fiddle http://jsfiddle.net/kc11/juo1e4at/#base that does the loop, but I'm not sure how to prepend each object's property-value pair. array unshift appears to be for arrays. I'd like a result of an object to look go from:

    Object { car="Audi A4 Avant", year=2011, available=true, more...}
    

    to:

    Object { checkbox=false, car="Audi A4 Avant", year=2011, available=true, more...}
    

    How can I make this happen

  • user1592380
    user1592380 over 9 years
    Thank you, that does answer the question the only issue is order ( or lack thereof ) in an object. Please see my note above.
  • user1592380
    user1592380 over 9 years
    Nit, Is it fair to say that although the ajax transmitted javascript objects from the server side do not have an order to their properties property this is set solely by the columns property which takes an array (ordered) of objects in handsontable?
  • Etheryte
    Etheryte over 9 years
    @user61629 Yes, that is correct. The order of the columns is defined by the columns configuration. If it isn't set there, the order may be arbitrary.