paco paco - 3 months ago 7
Javascript Question

Manipulate a key value pair to a string in Javascript

I need some help in manipulating a value pair array to return a string in a specific layout
This is the string i am trying to achieve:

'&test=id:1111|na:shoes|ca:shoe&test=id:2222|na:top|ca:tops'


This is the array I am trying to manipulate into my string

var prodlist =
[
{
name: 'shoe',
sku: '1111',
category: 'shoes'
},
{
name: 'top',
sku: '2222',
category: 'tops'
}
]


Here is what I have tried.

I added the 'deleteme' into the array thinking i could to a substitute later down the script.

function(){
var prods = prodlist;
var array = [];
for (var i = 0; i < prods.length; i++) {
var sku = (prods[i]['sku']);
var name = (prods[i]['name']);
var cat = (prods[i]['category']);

array.push({
deleteme: &test=id,
id: sku,
na: name,
ca: cat,
});
}
var newarray = array.toString();
return newarray;
}


At the moment this function returns '[object Object],[object Object]'

any help would be much appreciated.

Thanks

Answer

Quick and easy

function prods() {
     var prods = prodlist;
     var array = [];
     for (let product of prods)
        array.push('test=id:' + product.sku+ '|na:' + product.name + '|ca:' + product.category);
     return '&' + array.join('&');
}
Comments