Bit of background, this comes from a submitted form that I used serializeArray() on
I have a list of objects like so.
[
{name: 0, value: 'waffles'},
{name: 0, value: 'pancakes'},
{name: 0, value: 'french toast'},
{name: 1, value: 'pancakes'}
]
I want to take all things that have the same name attribute and put them together. EG,
[
{name: 0, value: ['waffles', 'pancakes', 'french toast']},
{name: 1, value: ['pancakes']}
]
how would one go about this? All the things I've tried only result in one answer being shown for each name key.
This should do it:
var newlist = _.map(_.groupBy(oldlist, "name"), function(v, n) {
return {name: n, values: _.pluck(v, "value")};
});
Here's the best I could come up with:
http://jsfiddle.net/Z6bdB/
var arr = [
{name: 0, value: 'waffles'},
{name: 0, value: 'pancakes'},
{name: 0, value: 'french toast'},
{name: 1, value: 'pancakes'}
]
var obj1 = {};
$.each(arr, function(idx, item) {
if (obj1[item.name]) {
obj1[item.name].push(item.value);
} else {
obj1[item.name] = [item.value];
}
});
var result = [];
for(var prop in obj1) {
result.push({
name: prop,
value: obj1[prop]
});
}
console.log(result);
This seems to work:
var output = _.chain(input)
.groupBy(function(x){ return x.name; })
.map(function(g, k) { return { name: k, value: _.pluck(g, 'value') }; })
.value();
Demonstration
I am one of those guys that uses native functions:
var food = [
{name: 0, value: 'waffles'},
{name: 0, value: 'pancakes'},
{name: 0, value: 'french toast'},
{name: 1, value: 'pancakes'}
];
var result = food.reduce(function(res,dish){
if (!res.some(function(d){return d.name === dish.name })){
var values = food.filter(function(d){ return d.name === dish.name }).map(function(d){ return d.value; });
res.push({name: dish.name, value : values});
}
return res;
}, []);
console.log(result);
I'd probably do something like this:
function them_into_groups(m, h) {
m[h.name] || (m[h.name] = [ ]);
m[h.name].push(h.value);
return m;
}
function them_back_to_objects(v, k) {
return {
name: +k,
value: v
};
}
var output = _(input).chain()
.reduce(them_into_groups, { })
.map(them_back_to_objects)
.value();
Using _.chain
and _.value
makes things flow nicely and using named functions make things less messy and clarifies the logic.
Demo: http://jsfiddle.net/ambiguous/G7qwM/2/