-1

嗨,我是 javascript 新手。我想使用它的值获取数组的索引并将新元素附加到该数组中。这是我的数组:

var testArray=[];

testArray.push({"key1":"value1","key2":"value2"});
testArray.push({"key1":"value11","key2":"value22"});

现在我想获取“value11”的索引,并将新元素附加为“key3”:“value33”在相同的索引中,如下所示:

testArray.push({"key1":"value11","key2":"value22","key3":"value33"});

请解释。提前致谢...

4

3 回答 3

1
var testArray=[];

testArray.push({"key1":"value1","key2":"value2"});
testArray.push({"key1":"value11","key2":"value22"});

var filtered = testArray.filter(function(item) {
    if (item.key1 == 'value11') {
        item.key3 = 'value33';
        return true
    }
    return false;
});

http://jsfiddle.net/XUzJw/

于 2013-01-26T07:07:41.373 回答
1

这是简单的答案:

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'));
于 2013-01-26T07:24:26.610 回答
0

你可以尝试类似的东西。即使您没有键名,此代码也可以使用。它在价值基础上找到键名。也将它添加到 jsFiddle http://jsfiddle.net/rTazZ/2/

var a = new Array(); 
a.push({"1": "apple", "2": "banana"}); 
a.push({"3": "coconut", "4": "mango"});

GetIndexByValue(a, "coconut");

function GetIndexByValue(arrayName, value) {  
var keyName = "";
var index = -1;
for (var i = 0; i < arrayName.length; i++) { 
   var obj = arrayName[i]; 
        for (var key in obj) {          
            if (obj[key] == value) { 
                keyName = key; 
                index = i;
            } 
        } 
    }
    //console.log(index); 
    return index;
} 
于 2013-01-26T07:45:19.843 回答