2016-06-16 89 views
2

所以我有一个数组JavaScript - 打印出阵列中具有相同名称的每个对象?

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),那么它应该会显示我在项目数组中的牛奶的2 ID's。我怎么能做到这一点? (是的,我不得不做出一个新的问题)

+0

如果您的例子中有3个,为什么只有2个ID(名称是'牛奶')? –

+2

你怎么知道你想要哪个ID,第一个2,最后2个? – JordanHendrix

+0

我的意思是,不只是2个人可以选择的人数。例如,如果他想要3,那么他选择3并显示这3个不同的ID。如果1然后一个ID等 –

回答

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));

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));

相关问题