[英]Extract specific values from multidimensional array javascript
我在下面看到一個多維數組。 我希望從中提取所有ingredients
值,然后對它們進行操作,例如計算每種成分中有多少。
var products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
{ name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
{ name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
{ name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];
我使用_.flatten()
, _.flatten()
和香草javascript函數map()
來完成此操作,但是我不得不兩次使用map()
。 一次提取所有成分,然后創建一個哈希樣式結構,該結構計算每種成分出現的次數。 我這些計數存儲在一個單獨的對象, ingredientCount
在這種情況下。
var ingredientCount = {};
_.flatten(products.map(function(x) {
return x.ingredients;
})).map(function(y){
return ingredientCount[y] = (ingredientCount[y] || 0) + 1;
});
console.log(ingredientCount);
將輸出以下列表:
{ artichoke: 1,
'sundried tomatoes': 2,
mushrooms: 2,
roma: 1,
'goats cheese': 1,
rosemary: 1,
'black beans': 1,
jalapenos: 1,
'blue cheese': 1,
garlic: 1,
walnuts: 1,
spinach: 1,
'kalamata olives': 1,
'sesame seeds': 1 }
我已經解決了我的問題,但是我覺得應該有一種更干凈,更有效的方法來執行此操作,而無需兩次使用map()
。 誰能幫我嗎? 如果這是一個重復的問題,我提前致歉。
這是我在普通JavaScript中可以想到的最優雅的方法,因為它不使用任何中間數據結構(原始解決方案創建了兩個數組,然后將它們組合成最終對象)。
var counts = products.reduce(function (result, product) {
product.ingredients.forEach(function (ingredient) {
result[ingredient] = (result[ingredient] || 0) + 1;
});
return result;
}, {});
您可以使用遞歸:
var products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; // written by hand, with <3 function ic(p,o,i,b,g) { i|=0;g|=0; if(!b&&p&&!p.ingredients) while((g=ic(p[g].ingredients,o,0,g+1))&&p[g]); else { o[p[i]]=(o[p[i]]|0)+1; return p[i+1]?ic(p,o,i+1,b):b; } } var ingredientCount = {}; ic(products, ingredientCount); document.body.innerHTML = JSON.stringify(ingredientCount).replace(/(\\,)/g,"$1<br/>");
body {font-family: monospace }
<body></body>
編輯:不,我不認真。 但是它快了將近3倍
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.