如果我有以下内容:
var dataContainer = [
{ id : 1, value : 5, qty : 73, orders: 7 },
{ id : 2, value : 6.15, qty : 212, orders: 49},
{ id : 3, value : 12.11, qty : 29, orders : 6}
];
如何使用JavaScript更新对象的值?我一直在尝试以下方法:
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
// I am updating the values in thisData
}
}
// Not sure what to do here in order to get thisData values back into dataContainer
}
所以我尝试弹出dataContainer[i]
并重新启动thisData
,但这不起作用。除非我做错了吗?我该怎么办?我感谢任何帮助。
答案 0 :(得分:1)
function UpdateValues(passedId, prop, newValue) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
thisData[prop] = newValue;
}
}
}
//Change qty to 99999 for object with index of 1
UpdateValues(1, "qty", 99999);
我添加了一个打印出结果的小提琴:http://jsfiddle.net/4UH9e/
答案 1 :(得分:1)
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
var data = dataContainer[i];
for (i in data) {
thisData[i] = data[i];
}
if (thisData.id == passedId) {
//Update the values in thisData.
}
}
//You still have the original data in dataContainer
}