最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select array index by object value - Stack Overflow

programmeradmin1浏览0评论

If I have an array like this:

var array = [{ID:1,value:'test1'},
             {ID:3,value:'test3'},
             {ID:2,value:'test2'}]

I want to select an index by the ID.

i.e, I want to somehow select ID:3, and get {ID:3,value:'test3'}.

What is the fastest and most lightweight way to do this?

If I have an array like this:

var array = [{ID:1,value:'test1'},
             {ID:3,value:'test3'},
             {ID:2,value:'test2'}]

I want to select an index by the ID.

i.e, I want to somehow select ID:3, and get {ID:3,value:'test3'}.

What is the fastest and most lightweight way to do this?

Share edited Apr 10, 2014 at 22:56 Dan 63.1k18 gold badges110 silver badges119 bronze badges asked Apr 10, 2014 at 22:54 Jacob PedersenJacob Pedersen 3472 gold badges4 silver badges13 bronze badges 3
  • What did you try so far? How did it work out? – Alex Wayne Commented Apr 10, 2014 at 22:56
  • Silly me experimenting with a for loop. – Jacob Pedersen Commented Apr 10, 2014 at 23:04
  • possible duplicate of Find object by id in array of javascript objects – Felix Kling Commented Apr 10, 2014 at 23:24
Add a ment  | 

5 Answers 5

Reset to default 5

Use array.filter:

var results = array.filter(function(x) { return x.ID == 3 });

It returns an array, so to get the object itself, you'd need [0] (if you're sure the object exists):

var result = array.filter(function(x) { return x.ID == 3 })[0];

Or else some kind of helper function:

function getById(id) {
    var results = array.filter(function(x) { return x.ID == id });
    return (results.length > 0 ? results[0] : null);
}
var result = getById(3);

With lodash you can use find with pluck-style input:

_.find(result, {ID: 3})

Using filter is not the fastest way because filter will always iterate through the entire array even if element being search for is the first element. This can perform poorly on larger arrays.

If you are looking for fastest way, simply looping through until the element is found might be best option. Something like below.

var findElement = function (array, inputId) {
    for (var i = array.length - 1; i >= 0; i--) {
        if (array[i].ID === inputId) {
            return array[i];
        }
    }
};

findElement(array, 3);

I would go for something like this:

function arrayObjectIndexOf(myArray, property, searchTerm) {
    for (var i = 0, len = myArray.length; i < len; i++) {
        if (myArray[i].property === searchTerm)
            return myArray[i];
    }
    return -1;
}

In your case you should do:

arrayObjectIndexOf(array, id, 3);
var indexBy = function(array, property) {
  var results = {};
  (array||[]).forEach(function(object) {
    results[object[property]] = object;
  });
  return results
};

which lets you var indexed = indexBy(array, "ID");

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>