如何动态地向javascript数组中的每个对象添加属性 [英] How to add properties dynamically to each object in an javascript array

查看:1024
本文介绍了如何动态地向javascript数组中的每个对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历对象数组,以便为​​每个对象添加属性和值.表的顺序很重要,因为我试图将handontable视图用作客户端来检索服务器端mysql表的内容.我希望handsontable视图具有与表相同的列顺序,但是我想插入复选框列作为第一列以允许选择记录.我有一个小提琴 http://jsfiddle.net/kc11/juo1e4at/#base 循环,但是我不确定如何在每个对象的属性-值对之前加上前缀.数组取消移位似乎是针对数组的.我想要一个对象的结果来自:

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...}

收件人:

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

我如何做到这一点

推荐答案

Javascript对象中属性的顺序无关紧要,它们不是严格排序的.
给定

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;
}

现在,回到Handsontable列顺序问题(这实际上是该问题的主要问题),您可以按以下方式对其进行定义:

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.

这篇关于如何动态地向javascript数组中的每个对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆