If I have the following:
如果我有以下内容:
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}
];
How do I update the value of the object using JavaScript? I have been trying the following:
如何使用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
}
So I tried to pop the dataContainer[i]
and push the thisData
back on but this didn't work. Unless I'm doing it incorrectly? What should I be doing here? I appreciate any help.
所以我尝试弹出dataContainer [i]并重新启动thisData,但这不起作用。除非我做错了吗?我该怎么办?我感谢任何帮助。
2 个解决方案
#1
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);
I've added a fiddle that prints out the result as well: http://jsfiddle.net/4UH9e/
我添加了一个小提琴,打印出结果:http://jsfiddle.net/4UH9e/
#2
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
}
#1
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);
I've added a fiddle that prints out the result as well: http://jsfiddle.net/4UH9e/
我添加了一个小提琴,打印出结果:http://jsfiddle.net/4UH9e/
#2
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
}