JavaScript - 打印出具有相同名称的数组中的每个对象?

时间:2016-06-16 15:32:02

标签: javascript arrays

所以我有一个数组

var items = [];
items.push({
    name: "milk",
    id: "832480324"
});
  items.push({
    name: "milk",
    id: "6234312"
});
 items.push({
    name: "potato",
    id: "983213"
});
  items.push({
    name: "milk",
    id: "131235213"
});

然后我有一个函数order(name, amount)。如果我将其称为order(milk, 2),那么它应该在items数组中显示2 ID's个牛奶。我怎么能实现这一目标? (是的,我不得不提出一个新问题)

2 个答案:

答案 0 :(得分:3)

使用simple for loop



var items = [];
items.push({
  name: "milk",
  id: "832480324"
});
items.push({
  name: "milk",
  id: "6234312"
});
items.push({
  name: "potato",
  id: "983213"
});
items.push({
  name: "milk",
  id: "131235213"
});

function order(name, count) {
  var res = [];
  // iterate over elements upto `count` reaches
  // or upto the last array elements
  for (var i = 0; i < items.length && count > 0; i++) {
    // if name value matched push it to the result array
    // and decrement count since one element is found
    if (items[i].name === name) {
      // push the id value of object to the array
      res.push(items[i].id);
      count--;
    }
  }
  // return the id's array
  return res;
}
console.log(order('milk', 2));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我喜欢的可读性功能ES6方法是使用filter().map().slice()

var items = [{name:"milk",id:"832480324"},{name:"milk",id:"6234312"},{name:"potato",id:"983213"},{name:"milk",id:"131235213"}];

function order(name, amount) {
  return items.filter(i => i.name === name)
              .map(i => i.id)
              .slice(0, amount);
}

console.log(order('milk', 2));