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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With