Request an array of javascript objects

Since my oop level in Javascript is not what I would like, this is my workaround for accessing an array of objects.

There is an object ( HelmT) in one array and one for the identifier, so I could easily access the first one id, and thus also access the real array and get the object using this "ID" property obtained from IDs.

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

... and you have Add- Remove and most importantlygetElementBy_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);
    }
};
+4
source share
1 answer

- . JavaScript , .

,

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>");
Hide result
+3

All Articles