This is a simple problem with a number of simple solutions, and I’m trying to figure out which is best. I would like a solution which is terse and readable.
Here’s the issue. I have an array of objects, and I want to combine several of the object members into pipe separated strings. As an example for this data:
[
{
foo: 1,
bar: 2
},
{
foo: 10,
bar: 20
}
]
I want to be able to create strings like this:
foo = "1|10";
bar = "2|20";
If the items were stored in separate arrays, this would be as simple as using Array.join.
Here’s my current solution:
var foo = "";
var bar = "";
var firstItem = obj.splice(0,1)[0];
foo = firstItem.foo.toString();
bar = firstItem.bar.toString();
obj.forEach(function (item) {
foo += "|" + item.foo.toString();
bar += "|" + item.bar.toString();
});
I also considered the following solution using Array.reduce, but browser support for this is still lacking. I am using Prototype, and it’s Array.reduce is unfortunately a completely different function than the native JS implementation.
var strings = obj.reduce(function (a, b) {
return {
a.foo.toString() + "|" + b.foo.toString(),
a.bar.toString() + "|" + b.bar.toString()
};
});
// value of strings is now:
// {
// foo: "1|10",
// bar: "2|20"
// }
Are there any more elegant ways to do this?
You could do this: