我的数据看起来像这样。
var data = [{
"ID": 1,
"bankRepaidAmt": "",
"Tasks": [{
ID: 5,
"chainPrefix": "1C",
"book": "Canada CRU",
}, ]
}]
现在,我正在尝试在“任务”下添加值为'13 / 1/17'的属性'scheduledDate'。我尝试使用以下语法。但它会引发错误。任何人都可以提供帮助。
data
.find(record => record.ID == '1')
.Tasks
.find(task => task.ID == '5')
.push({'bookedDate': '13/1/17'});
答案 0 :(得分:1)
您返回对象,以便可以使用Object.assign()
添加新属性。您也可以先检查是否找到了对象,然后添加属性。
var data = [{
"ID": 1,
"bankRepaidAmt": "",
"Tasks": [{
ID: 5,
"chainPrefix": "1C",
"book": "Canada CRU",
}]
}]
var obj = data.find(record => record.ID == '1').Tasks.find(task => task.ID == '5')
if(obj) Object.assign(obj, {'bookedDate': '13/1/17'})
console.log(data)
答案 1 :(得分:1)
var data = [{
"ID" : 1,
"bankRepaidAmt" : "",
"Tasks" : [{
ID : 5,
"chainPrefix" : "1C",
"book" : "Canada CRU",
},
]
}];
var x = data.find(record => record.ID == '1').Tasks.find(task => task.ID == '5').bookedDate = '13/1/17';
console.log(data);
答案 2 :(得分:0)
当您尝试将属性添加到对象时,您不需要推送 - 使用此功能:
data.find(record => record.ID == '1').Tasks.find(task => task.ID == '5')['bookedDate'] = '13/1/17';
见下面的演示:
var data = [{
"ID": 1,
"bankRepaidAmt": "",
"Tasks": [{
ID: 5,
"chainPrefix": "1C",
"book": "Canada CRU",
}, ]
}]
data.find(record => record.ID == '1').Tasks.find(task => task.ID == '5')['bookedDate'] = '13/1/17';
console.log(data);