【问题标题】:lodash create new json object from existing onelodash 从现有对象创建新的 json 对象
【发布时间】:2016-02-24 10:58:19
【问题描述】:

我想删除并重命名现有 JSON 对象的一些道具,以便将其与 select2/select2 查询插件一起使用 我需要转换的 JSON 对象是:

[
  {
    "id": 1,
    "type": "Subject1",
    "createdAt": "2016-02-19T23:03:12.000Z",
    "updatedAt": "2016-02-19T23:03:12.000Z",
    "Tags": [
      {
        "id": 1,
        "name": "sub1",
        "createdAt": "2016-02-19T23:03:12.000Z",
        "updatedAt": "2016-02-19T23:03:12.000Z",
        "tagType": 1
      }
    ]
  },
  {
    "id": 2,
    "type": "Subject2",
    "createdAt": "2016-02-19T23:03:12.000Z",
    "updatedAt": "2016-02-19T23:03:12.000Z",
    "Tags": [
      {
        "id": 16,
        "name": "sub2",
        "createdAt": "2016-02-19T23:03:12.000Z",
        "updatedAt": "2016-02-19T23:03:12.000Z",
        "tagType": 2
      }
    ]
  },
  {
    "id": 3,
    "type": "Subject3",
    "createdAt": "2016-02-19T23:03:12.000Z",
    "updatedAt": "2016-02-19T23:03:12.000Z",
    "Tags": [
      {
        "id": 22,
        "name": "sub3",
        "createdAt": "2016-02-19T23:03:12.000Z",
        "updatedAt": "2016-02-19T23:03:12.000Z",
        "tagType": 3
      }
    ]
  }
]

[
  {
    "text": "Subject1",
    "children": [
      {
        "id": 1,
        "text": "sub1"
      }
    ]
  },
  {
    "text": "Subject2",
    "children": [
      {
        "id": 16,
        "text": "sub2"
      }
    ]
  },
  {
    "text": "Subject3",
    "children": [
      {
        "id": 22,
        "text": "sub3"
      }
    ]
  }
]

我需要:

  1. 将名称和类型重命名为文本
  2. 删除 tagType、updatedAt 和 createdAt
  3. 将标签重命名为子标签
  4. 移除每个顶级对象的id

有没有办法使用 lodash 来完成这一切? 最好的方法是什么?

【问题讨论】:

标签: javascript json lodash


【解决方案1】:
var res = _.map(items, function(item){
    return {
       text: item.type,
       children: _.map(item.Tags, function(tag){
           return {
               id: tag.id,
               text: tag.name
           };
       })
    };
});

【讨论】:

    【解决方案2】:

    我通过嵌套两个 return 成功使用了这个链接: Creating new javascript Object form existing one

     var result = tags.map(function(obj) {
                    return {
                        text: obj.type,
                        childrens:obj.Tags.map(function(obj) {
                            return {
                                id : obj.id,
                                text : obj.name
                            }
                        })
                    };
                });
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2015-09-24
      • 2013-11-18
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2021-01-14
      相关资源
      最近更新 更多