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 = []";
2 Answers 2
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; }
answered Jul 22, 2019 at 21:23
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Jul 22, 2019 at 21:23
Jonas Wilms
139k20 gold badges164 silver badges164 bronze badges
Comments
lang-js
for(var i = 0; i < items.length; i++)butitemsis an object, not an array - it doesn't have alengthproperty. What are you trying to iterate? Properties?