lodash从现有的json对象创建新的json对象

时间:2016-02-24 10:58:20

标签: javascript json lodash

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

<rules>
    <rule name = "ToysRedirect" StopProcessing="true" />
    <match url = "^(.*)/besttoys$" />
    <action type = "Redirect" url = "{R:1}/bestcooltoys" appendQueryString="true" redirectType="Permanent"/>
    </rule>

[
  {
    "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
      }
    ]
  }
]

我需要:

  1. 将名称和类型重命名为文字
  2. 删除tagType,updatedAt和createdAt
  3. 将代码重命名为子代
  4. 删除每个顶级对象的ID
  5. 有没有办法用lodash做这一切? 最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

我通过嵌套两个返回来使用此链接成功: 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
                        }
                    })
                };
            });

答案 1 :(得分:0)

var res = _.map(items, function(item){
    return {
       text: item.type,
       children: _.map(item.Tags, function(tag){
           return {
               id: tag.id,
               text: tag.name
           };
       })
    };
});