问题描述:

Hi I am new to javascript. I want to get the index of array using its value and append new element into that array. Here is my array:

var testArray=[];

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

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

Now I want to get the index of "value11" and also append new element as "key3":"value33" in the same index as below:

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

Please explain. Thanks in advance...

网友答案:
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/

网友答案:

Here's the simple answer:

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;    
  }
}

The better answer looks more like this:

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'));
网友答案:

you can try something like. This code will work even when you do not have the key names. It finds key-names on basic of value. Had also added it to 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;
} 
相关阅读:
Top