基于JS中的一个属性值提取列表

时间:2018-02-15 14:48:18

标签: javascript underscore.js

我有这样的对象:

input = [  {value: 1,
    week: 1,
    year: 2017
   },
   {value: 10,
    week: 30;
    year: 2018
   },
   {value: 2,
    week: 2,
    year: 2018
   },
   {value:3,
    week: 3,
    year: 2017
   }
]

我想获得这个对象:

{ 2017: {value : [1, 3],
         week: [1, 3]
        },
  2018: {value : [10, 2],
         week: [30, 2]
        }
}

我从_.groupBy(input, function(elem) {return elem.year})开始,但后来我被困了。

2 个答案:

答案 0 :(得分:1)

您可以使用.reduce

let input = [{
    value: 1,
    week: 1,
    year: 2017
  },
  {
    value: 10,
    week: 30,
    year: 2018
  },
  {
    value: 2,
    week: 2,
    year: 2018
  },
  {
    value: 3,
    week: 3,
    year: 2017
  }
];

let result = input.reduce((c, v) => {
  c[v.year] = c[v.year] || {value: [], week: []};
  c[v.year].value.push(v.value);
  c[v.year].week.push(v.value);
  return c;
}, {});

console.log(result);

Doc:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

答案 1 :(得分:0)

使用lodash lib

var result = _(input)
                .mapKeys('year') 
                .mapValues(({ value, week }) => ({ value, week }))
                .value();

        console.log(result);


    /*

    { 
     2017: {
             value : [1, 3],
             week: [1, 3]
     },
      2018: { 
             value : [10, 2],
             week: [30, 2]
     }
    }

    */