0

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"
}
1
  • This is not JSON - JSON is a specifically formatted string. What you have is a JavaScript object. Commented Nov 14, 2017 at 12:25

2 Answers 2

1

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] )
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.