重新组合javascript数组

时间:2017-12-08 14:11:04

标签: javascript json lodash

我想格式化:

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null; // checking a.foo
}
const len = (a: A): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length; // okay
  }
  return 0;
} 

致:

[
    {
        "id": 1,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 2,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 3,
        "location": {
            "id": 2,
            "title": "location 2"
        },
    }
]

更新: 根据你的回答,我得出了:

[
    {
        "id": 1,
        "title": "location 1",
        "items": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ]
    },
    {   
        "id": 2,
        "title": "location 2",
        "items": [
            {
                "id": 3
            }
        ]
    }
]

哪个有效,但是项目对象仍然包含location属性,并且该位置仅维护其id属性。是否有必要将所有属性添加到groupBy?

我这样做的原因是因为我想过滤项目属性,但显示按位置分组的项目。

2 个答案:

答案 0 :(得分:0)

使用location.title上的_.groupBy(),然后map来收集项目。要创建对象,请使用location的键(第2个参数),使用_.get()从第1个项目中取出id,并映射其他项目以仅使用位置对象title使用_.omit()

const data = [{"id":1,"location":{"id":1,"title":"location 1"}},{"id":2,"location":{"id":1,"title":"location 1"}},{"id":3,"location":{"id":2,"title":"location 2"}}];

const result = _(data)
  .groupBy('location.title')
  .map((items, location) => ({
    location,
    id: _.get(items, '[0].id'), // get the 1st item (if any) id
    items: items.map(({ location }) => _.omit(location, 'title')) // map the objects and take the inner item without the title
  }))
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 1 :(得分:0)

替换以下代码

const result = _(items)
    .groupBy(x => x.location.id)
    .map((value, key) => ({location: key, items: value}))
    .value();

const result = _(items)
    .groupBy(x => x.location.id)
    .map((value, key) => ({location: key, items: value.map(e => ({id: e.id}))}))
    .value();