简体   繁体   中英

Create Array from other Arrays in an Object

I have an object that contains 3 arrays from which I need to create a new array.

This is what I have currently

function getItems(items)
{
    var returnArray = [];

    for(var i = 0; i < items.length; i++)
    {
        var item = items[i];   

        returnArray.push({ 
            id: item.product_sku,
            quantity: Math.round(item.product_quantity),
            price: item.product_price 
        });
    }

    return returnArray;
}

my_data = { product_price: "82.990000000, 26.750000000, 19.250000000", product_quantity: "1.000000000, 2.000000000, 1.000000000", product_sku: "1207, 1212, 1309" }


var viewBasket = JSON.stringify(getItems(my_data));

console.log("viewBasket = " + viewBasket);

This is what I'm expecting/hoping to see:

viewBasket  =  [ 
     { id: "1207", price: "82.990000000", quantity: "1.0" },
     { id: "1212", price: "26.750000000", quantity: "2.0" }, 
     { id: "1309", price: "19.250000000", quantity: "1.0" }
 ];

But it returns "viewBasket = []";

You could take an array with the wanted source and target keys and iterate the keys and map the values.

 var data = { checkout_pagename_url: "/checkout", order_total: "148.240000000", product_id: "126256, 126339, 131822", product_list_price: "82.990000000, 26.750000000, 19.250000000", product_discount: "0, 0, 0", product_name: "NorthShore AirSupreme Tab-Style Briefs, Medium, Case/60 (4/15s), NorthShore AirSupreme Tab-Style Briefs, Large, Pack/15, NorthShore FlexSupreme Pull-On Underwear, Large, Pack/14", product_quantity: "1.000000000, 2.000000000, 1.000000000", product_sku: "1207, 1212, 1309", product_price: "82.990000000, 26.750000000, 19.250000000", order_coupon_code: "" }, keys = [['product_sku', 'id'], ['product_price', 'price'], ['product_quantity', 'quantity']], viewBasket = keys.reduce((r, [source, target]) => data[source] .split(', ') .map((v, i) => Object.assign(r[i] || {}, { [target]: v })) , []); console.log(viewBasket);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

items is an object, not an array. You have to turn the strings into arrays first:

  const 
     prices = viewBasket.product_price.split(", "),
     quantities = viewBasket.product_quantity.split(", "),
     skus = viewBasket.product_sku.split(", ");

Then you can iterate over one of those by index, and access the values at the index of each of the arrays and build up objects from that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM