Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push an object in a specific order

I have an object, let's say

var obj = [{"name": "banana", "type": "fruit"},
           {"name": "carrot", "type": "vegetable"}];

And I need to add an object right after the first one [0] so I'll get the following:

var obj = [{"name": "banana", "type": "fruit"},
           {"name": "apple", "type": "fruit"},
           {"name": "carrot", "type": "vegetable"}];

needless to say I want it dynamic, and I'm trying to avoid loops for ease of use later down the road...

Is there any function like

obj.pushAfter(this['type'], "fruit", {"name": "apple", "type": "fruit"});

Type of function? P.S I'm using Jquery so that's an option

like image 681
gal zakay Avatar asked Sep 10 '25 13:09

gal zakay


1 Answers

While the accepted answer is informative and leads you to the right direction, if you are actually in need if a pushAfter function that does exactly what you described, you could roll your own like so...

function pushAfter(coll, k, v, add) {
  var matchIndex = coll.reduce(function(prevVal, currVal, i, arr) {
    if (currVal[k] === v) {
      return i;
    }
  });

  coll.splice(matchIndex + 1, 0, add);
}

var obj = [{"name": "banana", "type": "fruit"},
           {"name": "carrot", "type": "vegetable"}];

pushAfter(obj, 'type', "fruit", {"name": "apple", "type": "fruit"});
pushAfter(obj, 'name', "carrot", {"name": "radish", "type": "vegetable"});

This would yield:

[{
  name: "apple",
  type: "fruit"
}, {
  name: "banana",
  type: "fruit"
}, {
  name: "carrot",
  type: "vegetable"
}, {
  name: "radish",
  type: "vegetable"
}]

This finds your specified key and value within the given collection and splices in the new item at the matched index. Leveraging reduce in this case also provides a simple way to identify the match's index. Additionally, here's a working example.

like image 51
Seth Avatar answered Sep 13 '25 02:09

Seth