0

I have a javascript array and I need to detect the name in the javascript and then insert immediately after that item in the array. Prefer jQuery and javascript for solution.

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

I want to detect "Test3" and then insert this new array: {"name":"Test3.0001", "id":[3,6]}.

Using this technique but would like to add a function that detects the name and automatically splieces in or pushes in the new array using jQuery.

Community
  • 1
  • 1
user3250966
  • 139
  • 1
  • 13

3 Answers3

2

It would be simplest to just iterate through the array and then insert the item when you find the name you're looking for. Something like this ought to do it:

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

You'd then call it like this:

insertAtPoint(arrayExample, {name: "Test3.0001", id: [3, 6]}, "Test3"); // I've fudged this object because your example was invalid JS
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
2

Try this,

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

Subash Selvaraj
  • 3,385
  • 1
  • 14
  • 17
1

No need for splicing you can modify the object by reference Try this:

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

And you can call the function like this: modifyId(arrayExample, [2,4,5], 'Test1')

Elad Levy
  • 291
  • 3
  • 8
  • I don't want to replace the contents of an array, I want to insert a new array after the detected string/array row. – user3250966 Feb 26 '14 at 19:13