מוטי אינזנר מוטי אינזנר - 27 days ago 7
Javascript Question

Querying an object array javascript

As my level of oop in Javascript is not as I wish it was, this is my workaround to access an array of objects.

One array has the object (

HelmT
) and one for the id's so i could easily access first by
id
,and that way, also access the real array and get the object by it's "ID" property fetched from IDs array.

What is the correct way to manage an array of object?

... and off course have an
Add
-
Remove

and most important
getElementBy_SomeProperty()


var Objcoll ={
_CoreLstsIDs{_arr[],isready:false},
_CoreLsts{_arr[],isready:false},
HElmTColl_FindById: function (parId) {
var collindexofCurFileReadyDivWrpFlds = this.getIdxOfCurHElmTinColl_ID(parId);
return this._CorLsts._arr[collindexofCurFileReadyDivWrpFlds];
},
getIdxOfCurHElmTinColl_ID: function (parId) {
return $.inArray(parId, this._CorLstsIDs._arr);
}
};

Answer

The simplest way to manage an array is by treating it as an array. JavaScript Arrays have lots of functionality which you can leverage directly to achieve your goals.

For example,

var arr = [{
  id: 1,
  content: 'foo'
}, {
  id: 2,
  content: 'bar'
}, {
  id: 3,
  content: 'baz'
}];

var findById = function(id) {
  return arr.find(function(element) {
    return element.id === id;
  });
}

var findByProperty = function(prop, value) {
  return arr.find(function(element) {
    return element[prop] === value;
  });
}

findById(1) // {"id":1,"content":"foo"}
findById(2) // {"id":2,"content":"bar"}
findByProperty('content', 'baz') // {"id":3,"content":"baz"}

var arr = [{
  id: 1,
  content: 'foo'
}, {
  id: 2,
  content: 'bar'
}, {
  id: 3,
  content: 'baz'
}];

var findById = function(id) {
  return arr.find(function(element) {
    return element.id === id;
  });
}

var findByProperty = function(prop, value) {
  return arr.find(function(element) {
    return element[prop] === value;
  });
}

document.write("<pre>" + JSON.stringify(findById(1)) + "</pre>");
document.write("<pre>" + JSON.stringify(findById(2)) + "</pre>");
document.write("<pre>" + JSON.stringify(findByProperty('content', 'baz')) + "</pre>");

Comments