簡単な答えは次のとおりです。
var testArray = [];
testArray.push();
testArray.push();
// loop through every element of the array
for(var i = testArray, l = testArray.length; i < l; i++){
// grab this particular object
var obj = testArray[i];
// see if key1 is equivalent to our value
if(obj.key1 == 'value11'){
// if so, set key3 to the value we want for this object
obj.key3 = 'value33';
break;
}
}
より良い答えは次のようになります。
var testArray = [
{
"key1" : "value1",
"key2" : "value2"
},
{
"key1" : "value11",
"key2" : "value22"
}
];
function findAndSwap(list, comparator, perform){
var l = list.length;
while(l--) if(comparator(list[l], l, list)) perform(list[l], l, list);
}
function checkProp(prop, value){ return function(obj){ return obj[prop] === value } }
function addProp (prop, value){ return function(obj){ obj[prop] = value } }
findAndSwap(testArray, checkProp('key1', 'value11'), addProp('key3', 'value33'));