【问题标题】:underscore for multiple nested level arrays多个嵌套级别数组的下划线
【发布时间】:2017-04-24 09:06:13
【问题描述】:

我有一个对象数组,我想将其转换为以id 为键的键值对映射。但是,我想在根级别和 recipes 属性中都这样做。

数组resp

[
  {
    "id": "1",
    "recipes": [
      {
        "id": 4036
      },
      {
        "id": 4041
      }
    ]
  },
  {
    "id": "2",
    "recipes": [
      {
        "id": 4052
      },
      {
        "id": 4053
      }
    ]
  }
]

期望的结果

{
  "1": {
    "id": "1",
    "recipes": {
      "4036": {
        "id": 4036
      },
      "4041": {
        "id": 4041
      }
    }
  },
  "2": {
    "id": "2",
    "recipes": {
      "4052": {
        "id": 4052
      },
      "4053": {
        "id": 4053
      }
    }
  }
}

我知道如何通过以下函数使用 lodash:

使用 Underscore.js

function deepKeyBy(arr, key) {
  return _(arr)
    .map(function(o) { // map each object in the array
      return _.mapValues(o, function(v) { // map the properties of the object
        return _.isArray(v) ? deepKeyBy(v, key) : v; // if the property value is an array, run deepKeyBy() on it
      });
    })
    .keyBy(key); // index the object by the key
}

然而,对于这个项目,我正在寻找一个优雅的解决方案,使用下划线来做同样的事情 - 使嵌套在数组中的所有对象都使用 id 作为键。有人知道怎么做吗?

谢谢!

编辑:添加了所需的输出格式

【问题讨论】:

  • 你能展示预期结果的结构吗?
  • @hackerrdave 我已经在上面添加了想要的结果

标签: javascript arrays json object underscore.js


【解决方案1】:

我会在响应中使用Array.reduce,并在配方中使用嵌套的Array.reduce 以产生所需的结果。这是一个 es6 示例:

resp.reduce((p, c) => {
  p[c.id] = {
    id: c.id,
    recipes: c.recipes.reduce((r, cr) => {
       r[cr.id] = { id: cr.id }
       return r;
    }, {})
  }
  return p;
}, {});

一个更详细的非 es6 版本:

var resp = [
  {
    "id": "1",
    "recipes": [
      {
        "id": 4036
      },
      {
        "id": 4041
      }
    ]
  },
  {
    "id": "2",
    "recipes": [
      {
        "id": 4052
      },
      {
        "id": 4053
      }
    ]
  }
]    

var formatted = resp.reduce(function(data, cur) {
  data[cur.id] = {
    id: cur.id,
    recipes: cur.recipes.reduce(function(recips, curRecip) {
       recips[curRecip.id] = { id: curRecip.id }
       return recips;
    }, {})
  }
  return data;
}, {});

console.log(formatted);

如果您必须使用下划线,您可以将respc.recipes 换行:

_(resp).reduce((p, c) => {
  p[c.id] = {
    id: c.id,
    recipes: _(c.recipes).reduce((r, cr) => {
       r[cr.id] = { id: cr.id }
       return r;
    }, {})
  }
  return p;
}, {});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多