javascript - 下划线表示多个嵌套级别数组

标签 javascript arrays json object underscore.js

我有一个对象数组,我想将其转换为以 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 作为键。有人知道该怎么做吗?

谢谢!

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

最佳答案

我会在响应上使用 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;
}, {});

关于javascript - 下划线表示多个嵌套级别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051052/

相关文章:

java - 像间隔 java 一样将元素插入到 ArrayList

c - 快速排序分区函数的参数

javascript - 如何访问本地 JSON 数组中的图像

javascript - ESLint 未检测到导入的 React 组件

java - 在类数组中使用 'contains' 方法

javascript - 在 Node 中使用命令行创建文件

php - 无法解码 JSON stripslashed 字符串?

json - 记录数据验证

javascript - 全高 div 固定

javascript - 更改数据表中使用的参数 ajax url.Action on Ajax.reload