2014-02-26 16 views
0

我有一個JavaScript數組,我需要在javascript中檢測該名稱,然後在數組中的該項之後立即插入。傾向於使用jQuery和JavaScript解決方案。在與數組中的名稱匹配的行後插入一行

var arrayExample = 
[{"name":"Test1","id":[1]}, 
{"name":"Test2","id":[2]}, 
{"name":"Test3","id":[3]}, 
{"name":"Test4","id":[4]}, 
{"name":"Test5","id":[5]}]; 

我想檢測 「Test3的」,然後插入這個新的數組:{ 「名」: 「Test3.0001」, 「ID」:[3,6]}。

使用this technique,但想添加一個函數來檢測名稱並自動使用jQuery插入或推入新數組。

回答

2

只需遍歷數組,然後在找到要查找的名稱時插入該項目將是最簡單的。像這樣的東西應該做到這一點:

function insertAtPoint(arr, item, searchTerm) { 
    for(var i = 0, len = arr.length; i<len; i++) { 
     if(arr[i].name === searchTerm) { 
      arr.splice(i, 0, item); 
      return; // we've already found what we're looking for, there's no need to iterate the rest of the array 
     } 
    } 
} 

你會再這樣稱呼它:

insertAtPoint(arrayExample, {name: "Test3.0001", id: [3, 6]}, "Test3"); // I've fudged this object because your example was invalid JS 
1

無需拼接,你可以通過引用修改對象 試試這個:

var modifyId = function(arr, idArr, term) { arr.forEach(function(item){ if(item.name == term) { item.id = idArr; } }) }

而且你可以調用這樣的功能: modifyId(arrayExample, [2,4,5], 'Test1')

+0

我不想替換數組的內容,我想檢測的串/矩陣行後插入一個新的陣列。 – user3250966

2

試試這個,

function insertItem(obj,searchTerm){ 
    $.each(arrayExample,function(i,item){ 
     if(item.name == searchTerm){ 
      arrayExample.splice(i+1,0,obj); 
      return false; 
     } 
    }); 
} 

insertItem({"name":"Test3.0001","id":[3,6]},"Test3"); 

FIDDLE

相關問題