[英]Javascript: How to Combine & Filter Arrays
我有3個需要轉換為數組的字符串,從那里我要過濾,然后使用javascript進行合並,我需要注意的是,我使用的是Zapier,它們的javascript庫有點有限,但這就是我所擁有的遠:
字串:
var type = 'bundle, simple, simple';
var name = 'Product1, Product2, Product3';
var price = '1.99, 2.99, 3.99';
我需要弄清楚如何使用javascript將上面的3個字符串轉換為以下數組:
var itemArray = [
{type:"bundle", info: {name: "Product1", price: "1.99"}},
{type:"simple", info: {name: "Product2", price: "2.99"}},
{type:"simple", info: {name: "Product3", price: "3.99"}}];
從那里開始,我希望過濾出bundle
產品類型,並且只傳遞simple
產品數組,為此,我需要執行以下操作:
// Using a for loop
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
var item = itemArray[i];
if (item.type == 'simple') filtered.push(item);
}
return {filtered}; //this returns just the 2 simple product type arrays
所以我的問題是,我該如何開始使用這3個字符串,並使用javascript將其轉換為itemArray
格式?
您可以使用map
和filter
的組合來首先組合您擁有的三個數組,然后過濾掉匹配item_type='bundle'
數組。
var item_type = ['bundle', 'simple', 'simple'], item_name = ['product1', 'product2', 'product3'], item_price = [1.99, 2.99, 3.99], res = item_type.map(function(v,i) { //combine arrays return [v, { [item_name[i]]: item_price[i] }]; }).filter(function(o) { // only allow items where 'item_type' is not "bundle" return o[0] != "bundle"; }); console.log(JSON.stringify(res, 2, null));
是的... JS缺少Array.prototype.zip()
功能。 讓我們發明它並相應地解決。
Array.prototype.zip = function(...a){ return this.map((e,i) => [e].concat(a.map(sa => sa[i]))); }; var itemType = ["bundle", "simple", "simple"], itemName = ["product1", "product2", "product3"], itemPrice = [1.99,2.99,3.99], result = itemType.zip(itemName,itemPrice) .map(sa => [sa[0],{[sa[1]]:sa[2]}]) .filter(t => t[0] === "simple"); console.log(result);
PS:我已經交換了最后一個.map()
和.filter()
函數的位置,以適應您的要求,但是修改SO時不鼓勵在以前的答案中進行更改的問題。
首先,通過map
將它們全部組合成一個對象數組,然后進行filter
,然后再次map
成所需的表示形式。 就像是:
item_type
.map((type, index) => ({
type,
index,
name: item_name[index],
price: item_price[index]
}))
.filter(el => el.type === 'simple')
.map(el => [el.type, {name: el.name, price: el.price}])
您可以過濾列,轉置數組並構建所需的內部數組。
var item_type = ['bundle', 'simple', 'simple'], item_name = ['product1', 'product2', 'product3'], item_price = [1.99, 2.99, 3.99], result = [item_type, item_name, item_price] .map((a, _, aa) => a.filter((b, i) => aa[0][i] !== 'bundle')) .reduce((r, a, i) => (a.forEach((b, j) => (r[j] = r[j] || [], r[j][i] = b)), r), []) .map(a => ({ type: a[0], info: { name: a[1], price: a[2] } })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.