2016-06-16 35 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));

相關問題