过滤对象的数组/数组转换成另一种 [英] Filter an array of objects / convert array into another

查看:131
本文介绍了过滤对象的数组/数组转换成另一种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以请帮我在这样的格式数据转换:

 坦克:[
      {
          ID:1
          名称: {
              标识:1,
              器:000
          },
          输入:{
              标识:1,
              系统:CV-001
          }
      }
  ]

 坦克:[
      {
          类型:1,
          名:1
      }
  ]

正如你所看到的,type.id在第一阵列中是只要输入第二个是一样的。这就像我通过数组迭代(因为我有它不只有一个对象)和对象只留下需要的领域,但我卡住了。
希望这是给你们的一点信息。


解决方案

您可以用一个简单的 Array.map()

\r
\r

VAR OBJ = {\r
  坦克:\r
    {\r
      ID:1\r
      名称: {\r
        标识:1,\r
        器:000\r
      },\r
      输入:{\r
        标识:1,\r
        系统:CV-001\r
      }\r
    },\r
    {\r
      ID:2\r
      名称: {\r
        ID:2,\r
        器:200\r
      },\r
      输入:{\r
        ID:2,\r
        系统:CV-002\r
      }\r
    }\r
  ]\r
};\r
\r
obj.tanks = obj.tanks.map(函数(项目){\r
  返回{\r
    名称:item.name.id,\r
    类型:item.type.id\r
  };\r
});\r
\r
的console.log(OBJ);

\r

&LT;脚本src=\"http://gh-canon.github.io/stack-snippet-console/console.min.js\"></script>\r
\r
\r

could you please help me to convert data in format like :

"tanks": [
      {
          "id": "1",
          "name": {
              "id": 1,
              "tor": "000"
          },
          "type": {
              "id": 1,
              "system": "CV-001"
          }
      }
  ]

into

"tanks":[
      {
          "type": 1,
          "name": 1 
      }
  ]

As you can see, type.id in the first array is the same as just type in the second. It is like I have to iterate through the array(as I have not only one Object in it) and left only needed fields in Objects, but I am stuck. Hope it is a little informative for you.

解决方案

You can do this with a simple Array.map()

var obj = {
  tanks : [
    {
      "id": "1",
      "name": {
        "id": 1,
        "tor": "000"
      },
      "type": {
        "id": 1,
        "system": "CV-001"
      }
    },
    {
      "id": "2",
      "name": {
        "id": 2,
        "tor": "200"
      },
      "type": {
        "id": 2,
        "system": "CV-002"
      }
    }
  ] 
};

obj.tanks = obj.tanks.map(function(item) {
  return { 
    name : item.name.id,
    type : item.type.id
  };
});

console.log(obj);

<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

这篇关于过滤对象的数组/数组转换成另一种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆