consolidating values in a list of objects based on

2019-07-20 05:14发布

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.

5条回答
做个烂人
2楼-- · 2019-07-20 05:43

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);
查看更多
Animai°情兽
3楼-- · 2019-07-20 05:44

This should do it:

var newlist = _.map(_.groupBy(oldlist, "name"), function(v, n) {
    return {name: n, values: _.pluck(v, "value")};
});
查看更多
Emotional °昔
4楼-- · 2019-07-20 05:53

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/

查看更多
可以哭但决不认输i
5楼-- · 2019-07-20 06:00

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

查看更多
Anthone
6楼-- · 2019-07-20 06:03

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);
查看更多
登录 后发表回答