您好我是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"});
请解释一下。提前谢谢......
答案 0 :(得分: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;
});
答案 1 :(得分: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'));
答案 2 :(得分: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;
}