Lodash组对象数组,并返回键数组,而不是对象

时间:2019-02-06 17:05:46

标签: javascript arrays lodash

我有一个这样的对象数组

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"}]

使用_.groupBy(data,"age")将返回name作为带有对象数组的键。

如何仅返回name数组?

4 个答案:

答案 0 :(得分:0)

使用_.flow()创建一个按age分组的函数,然后使用_.mapValues()映射组,并使用_.map()从数组中抽取名称:

const { flow, groupBy, mapValues, map } = _

const fn = flow(
  arr => groupBy(arr, 'age'),
  groups => mapValues(groups, g => map(g, 'name'))  
)

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

以及更短的lodash/fp版本:

const { flow, groupBy, mapValues, map } = _

const fn = flow(
  groupBy('age'),
  mapValues(map('name'))
)

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"}]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

答案 1 :(得分:0)

更新

  

感谢您的帮助,我需要一个密钥作为年龄,一个值作为数组   仅名称而不是对象,我已经编辑了问题

在这种情况下,您可以使用reduce

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"},{name:'abc', age:'23'}]


const op = data.reduce((out,{name,age})=>{
  if(out[age]){
    out[age].push(name)
  } else {
    out[age] = [name]
  }
  return out
},{})

console.log(op)
只需使用map

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"}]

const op = data.map(({name}) => name)

console.log(op)

@ori要求唯一名称时,如果您只想使用唯一名称,则可以使用Set

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"},{name:'abc', age:'23'}]

const op = [...new Set(data.map(({name}) => name))]

console.log(op)

答案 2 :(得分:0)

使用Array#reduce

const data = [{name:"abc",age:"18"},{name:"dfd",age:"18"},{name:"dnss",age:"20"},{name:"dnnns",age:"12"}]

const res = data.reduce((a,{name,age})=>{
  if(!a[age]) a[age] = [];
  a[age].push(name);
  return a;
}, {});

console.log(res);

答案 3 :(得分:0)

分组后,您需要遍历每个组并仅返回名称:

const res = _.chain(data)
    .groupBy('age')
    .mapValues(group => _.map(group, 'name'))
    // or with FP .mapValues(_.partial(_.map, _, 'name'))
    .value();