在现有数组中添加额外的元素和值

时间:2019-03-28 08:28:57

标签: jquery

我有一个这样的数组

  

详细信息:{0:{TruckAllocationId:1,RefTaskId:3,RefTruckId:7,   TruckNo:“ TH56445565”,DriverName:“ driver”} 1:{TruckAllocationId:2,   RefTaskId:3,RefTruckId:9,TruckNo:“ 88989798990”,DriverName:   “ dasdah”}}

我必须在上面的数组中添加更多的值

示例我想添加新元素,并在下面的数组中添加值0th和1st数组年龄

  

0:{TruckAllocationId:1,RefTaskId:3,RefTruckId:7,TruckNo:   “ TH56445565”,DriverName:“ driver”,年龄:16} 1:{TruckAllocationId:2,   RefTaskId:3,RefTruckId:9,TruckNo:“ 88989798990”,DriverName:   “ dasdah”,年龄:18}

我尝试下面的代码不起作用

dist/

帮助我解决上述问题

3 个答案:

答案 0 :(得分:1)

您的名为“ details”的对象不是数组,而是对象。如果要保留它,只需将属性名称用作字符串。像"0": {....}。 因此,您应该使用对象属性更改/删除/添加值。 像rowA.details[i].DriverName = "Name"rowA.details[i]["DriverName"] = "Name"

如果您不想保留该对象的“详细信息”,请删除属性并将其设置为实际数组。然后您的代码将起作用。像details = [{}, {}, ...]

答案 1 :(得分:0)

变量包含对象文字而不是数组。您可能需要先将其转换为数组或在对象上循环。

  

转换为数组

var rowA = {
  'details': {
    '0': {'TruckAllocationId': 1, 'RefTaskId': 3, 'RefTruckId': 7, 'TruckNo': 'TH56445565', 'DriverName': 'driver'},
    '1': {'TruckAllocationId': 2, 'RefTaskId': 3, 'RefTruckId': 9, 'TruckNo': '88989798990', 'DriverName': 'dasdah'}
  }
};


if (typeof rowA.details != 'undefined') {
  rowA.details = Object.values(rowA.details);
  for (var i = 0; i < rowA.details.length; i++) {
    // Your action here
    rowA.details[i]['Age'] = Math.floor(Math.random() * 10) + 20;
    console.log(rowA.details[i]);
  }
}

  

将对象放在对象上

var rowA = {
  'details': {
    '0': {'TruckAllocationId': 1, 'RefTaskId': 3, 'RefTruckId': 7, 'TruckNo': 'TH56445565', 'DriverName': 'driver'},
    '1': {'TruckAllocationId': 2, 'RefTaskId': 3, 'RefTruckId': 9, 'TruckNo': '88989798990', 'DriverName': 'dasdah'}
  }
};


if (typeof rowA.details != 'undefined') {
  for (key in rowA.details) {
    // Your action here
    // key is the Key of the object
    // to pass anything to the current index use rowA.details[key]
    // Example : rowA.details[key] = 'Amazing'
    rowA.details[key]['Age'] = Math.floor(Math.random() * 10) + 20;
    console.log(key, rowA.details[key]);
  }
}

答案 2 :(得分:0)

我假设您的details是一个数组,所以这是您可以用来实现所需目标的方法。

details = [
{TruckAllocationId: 1, RefTaskId: 3, RefTruckId: 7, TruckNo: "TH56445565", DriverName: "driver"},
{TruckAllocationId: 2, RefTaskId: 3, RefTruckId: 9, TruckNo: "88989798990", DriverName: "dasdah"}
]
details[0]['Age'] = 16
details[1]['Age'] = 18
console.log(details)