ldmo
ldmo

Reputation: 379

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...

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"
}

Upvotes: 0

Views: 494

Answers (2)

Nicholas Pesa
Nicholas Pesa

Reputation: 2196

If you want to use a JSONArray it should be formatted like so:

  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. The object keys as names are redundant as you also have a 'name' field in the 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. I hope this can be of some help for what you are trying to do.

Upvotes: 1

Christian Benseler
Christian Benseler

Reputation: 8065

Use Object.keys(object) to iterate over object's keys, it will return an array, and then use array's map method to iterate over this array of keys and return each item from the json object and assign it to a position in an array.

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

Upvotes: 1

Related Questions