过滤对象数组

时间:2016-11-05 15:33:40

标签: javascript arrays object for-loop

我有一个像这样的数组:

const xx = [
  {
    name: "Alex",
    income: 324300,
    total: 3030000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  }
];

我想检查收入是否大于300000,如果是,则会存储或记录他们的名字。

这是我试过的,我不完全理解它是如何工作的。

var f = {};
for (var i = 0, len = xx.length; i < len; i++) {
    f[xx[i].id] = xx[i];
    if(f[income]>=500000){
        console.log(xx[i]);
    }
}

3 个答案:

答案 0 :(得分:2)

您可以使用Array.filter过滤数组,使用Array.forEach将其迭代到console.log或者您想要使用它。

const xx = [
  {
    name: "Alex",
    income: 324300,
    total: 3030000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  },
  {
    name: "Wake",
    income: 4,
    total: 3
  }
];

xx.filter(function(x) {
  return x.income > 30000;
}).forEach(function(x){
  console.log(x)
});

答案 1 :(得分:1)

在ES5中,您可以使用过滤器来获取一个数组,其中包含总数为&gt;的元素。 300000

&#13;
&#13;
var data = [
  {
    name: "Alex",
    income: 324300,
    total: 30000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  }
];
var result = data.filter(x => x.total > 300000);
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:-2)

使用过滤器 检查此代码段

&#13;
&#13;
const xx = [
  {
    name: "Alex",
    income: 324300,
    total: 3030000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  }
];
xx.filter(function(item){
  if(item.income>324300)
    alert(item.name);
})
&#13;
&#13;
&#13;

希望这有帮助

相关问题