JSFiddle - React, Tailwind, and code Playground
by SmokeyPHP
JavaScript
OArrTool = {
_store: {}
,add: function(arr,obj) {
arr.push(obj);
//Store an array of indexes that hold this key value
if(typeof OArrTool._store[obj.key] == "undefined") OArrTool._store[obj.key] = [];
OArrTool._store[obj.key].push(arr.indexOf(obj));//Could alternately use arr.length if confident of no deleted indexes etc
return arr;
}
,getByKey: function(arr,key) {
for(var i in OArrTool._store[key]) //Loop through the indexes that hold this key
{
var arrI = OArrTool._store[key][i];
//Check that this array index is relevant to this array
if(arr[arrI].key==key) return arr[arrI];
}
}
}
var arr = [];
var o1 = {id: 0, key: "A", data: "W"};
var o2 = {id: 1, key: "B", data: "X"};
var o3 = {id: 2, key: "C", data: "Y"};
var o4 = {id: 3, key: "D", data: "Z"};
arr = OArrTool.add(arr,o1);
arr = OArrTool.add(arr,o2);
arr = OArrTool.add(arr,o3);
arr = OArrTool.add(arr,o4);
var obj = OArrTool.getByKey(arr,'D')
document.body.innerHTML = obj.data;