简体   繁体   English

为angular2创建管道以将JSON迭代到数组

[英]Create pipe for angular2 for iterating JSON to array

I'm trying to use the following JSON data and convert it into an array, so I can run *ngFor='let item of items' and display data in terms of item.name etc... 我正在尝试使用以下JSON数据并将其转换为数组,因此我可以运行*ngFor='let item of items'并根据item.name等显示数据...

I tried the following: 我尝试了以下方法:

var out = [];
for(var key1 in object) {
    out[key1] = key1;
  for(var key2 in object[key1]) {
    for(var key3 in object[key2]) {
        out[key1][key2] = key3;
        }
  }
  console.log(out);
}

But Im just getting the title as key and value. 但是我只是把标题作为关键和价值。

var object = {
  "compressorClutch": {
    "name": "compressorClutch",
    "param": "Y",
    "register": "64",
    "type": "b"
  },
  "batteryLive": {
    "name": "batteryLive",
    "param": "Y",
    "register": "53",
    "type": "b"
  },
  "batteryGround": {
    "name": "batteryGround",
    "param": "Y",
    "register": "85",
    "type": "b"
  },
  "mainsCable": {
    "name": "mainsCable",
    "param": "N",
    "register": "",
    "type": "b"
  },
  "kcb": {
    "name": "kcb",
    "param": "13",
    "register": "337",
    "type": "i"
  },
  "config": "LorA-F"
}

使用Object.keys(object)遍历对象的键,它将返回一个数组,然后使用数组的map方法遍历此键的数组,并从json对象返回每个项目,并将其分配给数组中的某个位置。

const items = Object.keys(object).map( key => object[key] )

If you want to use a JSONArray it should be formatted like so: 如果要使用JSONArray,则应采用以下格式:

  object = [
    {
      'name': 'compressorClutch',
      'param': 'Y',
      'register': '64',
      'type': 'b'
    },
    {
      'name': 'batteryLive',
      'param': 'Y',
      'register': '53',
      'type': 'b'
    },
    {
      'name': 'batteryGround',
      'param': 'Y',
      'register': '85',
      'type': 'b'
    },
    {
      'name': 'mainsCable',
      'param': 'N',
      'register': '',
      'type': 'b'
    },
    {
      'name': 'kcb',
      'param': '13',
      'register': '337',
      'type': 'i'
    }
  ];

That is capable of being used in an *ngFor easily to display the data. 可以在*ngFor使用*ngFor轻松显示数据。 The object keys as names are redundant as you also have a 'name' field in the JSONObject. 作为名称的对象键是多余的,因为您在JSONObject中也有一个“名称”字段。 To find the right object that matches maybe a search query such as 'mainCables' you could just filter the array based on one of the object values. 要找到可能与诸如“ mainCables”之类的搜索查询匹配的正确对象,您可以仅基于对象值之一过滤数组。 I hope this can be of some help for what you are trying to do. 我希望这可以对您尝试做的事情有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM