-1

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...

Babu R
  • 1,025
  • 8
  • 20
  • 40

3 Answers3

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/

salexch
  • 2,644
  • 1
  • 20
  • 17
1

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'));
THEtheChad
  • 2,372
  • 1
  • 16
  • 20
  • No problem, this is probably really hard to digest for a beginner, but you might want to study it, because it has tremendous flexibility. – THEtheChad Jan 26 '13 at 07:34
0

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;
} 
Atur
  • 1,712
  • 6
  • 32
  • 42