0

I am not sure how to phrase this question but I hope it is understandable

In Angular 6 I have a GET request that returns a JSON object like this


"fieldA": [
 {
   "displayValue": "value1", 
   "id": "A"
 }, 
 {
   "displayValue": "value2", 
   "id": "B"
 } 
  ], 
"fieldB": [
 {
   "displayValue": "value1", 
   "id": "0"
 }, 
 {
   "displayValue": "value2", 
   "id": "1"
 }, 
 ], 
"FieldC": [
 {
   "displayValue": "value1", 
   "id": "47"
 }, 
 {
   "displayValue": "valuen", 
    "id": "94"
 }, 
 ] 
}"fieldA": [
 {
   "displayValue": "value1", 
   "id": "A"
 }, 
 {
   "displayValue": "value2", 
   "id": "B"
 } 
  ], 
"fieldB": [
 {
   "displayValue": "value1", 
   "id": "0"
 }, 
 {
   "displayValue": "value2", 
   "id": "1"
 }, 
 ], 
"FieldC": [
 {
   "displayValue": "value1", 
   "id": "47"
 }, 
 {
   "displayValue": "valuen", 
    "id": "94"
 }, 
 ] 
}

if I iterate over this with this code

for(let item in this.response) {
    console.log(item);
    this.schFields.push(item);
}

I correctly get each of the field names. There could be a variable number of field names each with variable numbers of values

Now I need to list the values for each of the fields stored in the schFields array

I cannot see how to use the value read from the array as a variable

if I know the field name then it works fine, like

for(let item of this.response.fieldA) {
    let itemelem = { "entity_id" : item.id, "entity_name" : item.displayValue };
    this.items.push(itemelem);
}

but when the fieldA part needs to be a variable I have not been able to find a solution.

Seanny123
  • 8,776
  • 13
  • 68
  • 124
  • You can take a look [here](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript). Create an object and then use the square brackets to add dynamic properties to the object. Something like `var yourObject['yourString'] = yourData`. If you want to access the keys of your object, you can use the following `Object.keys(yourObject)`. – riorudo Jun 26 '19 at 17:22

2 Answers2

0

Not sure if I understand the question correctly, but you can access an object attribute using a string.

const data = {fieldA: "data1", fieldb: "data2"};
console.log(data["fieldA"]); //will print data1

so you can do this

const keys = Object.keys(this.schFields); // to get ["FieldA", "FieldB", ...]
keys.map(fieldKey => {
  console.log(this.response[fieldKey]);
});
0

Whatever you are trying to do in your last for loop, I think this below code will do that.

for (let key in this.response) {
    for(let item of this.response[key]) {
        let itemelem = { "entity_id" : item.id, "entity_name" : item.displayValue };
        this.items.push(itemelem);
    }
}
Mazedul Islam
  • 1,543
  • 1
  • 11
  • 15