简体   繁体   English

遍历对象时未定义array.filter

[英]array.filter is undefined when looping over objects

I have an array of objects where the value i'm trying to find is a number, i'm wanting to return the underlying objects array when the correct number is found, and the value i'm passing to search is type number. 我有一个对象数组,其中我要查找的值是一个数字,我想在找到正确的数字时返回基础对象数组,而我传递给搜索的值是类型数字。

I keep getting "array.filter is undefined" error. 我不断收到“ array.filter未定义”错误。 I'm assuming it's because the structure is one object and not an array? 我假设这是因为结构是一个对象而不是数组? Whats the best way to do this? 最好的方法是什么?

I have a fiddle here 在这里摆弄

  var obj = array.filter(function ( obj ) {
    return obj === 2000;
  })[0];

  console.log( obj );

Your "array" is not an array - its an object 您的“数组”不是数组-它是一个对象

var array = {
  "legend": {
     ....
  }
}

What you want instead is just read properties of an object - some of them are numeric, which means you'll need the square bracket notation: 相反,您想要的只是读取对象的属性-其中一些是数字的,这意味着您需要方括号表示法:

 var obj = array.legend["2000"];

Updated fiddle: http://jsfiddle.net/gJPHw/221/ 更新的小提琴: http : //jsfiddle.net/gJPHw/221/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM