consolidating values in a list of objects based on an attribute which is the same

做~自己de王妃 提交于 2019-12-11 02:49:18

问题


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.


回答1:


This should do it:

var newlist = _.map(_.groupBy(oldlist, "name"), function(v, n) {
    return {name: n, values: _.pluck(v, "value")};
});



回答2:


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);



回答3:


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




回答4:


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);



回答5:


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/



来源:https://stackoverflow.com/questions/21469613/consolidating-values-in-a-list-of-objects-based-on-an-attribute-which-is-the-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!