Home > Mobile >  how to display value if the value is a key
how to display value if the value is a key

Time:04-13

I have this object but the value has the key element and wondering how to grab the value

For example:

2:
    values: 123
3:
    values:
        10.0: 456

The code:

 <td>{  agg[2].values}</td>
 <td>{  agg[3].values}</td>

The HTML:

<td>123</td>
<td></td>

The issue:

I want to display the value "456" in the second "td" but the code is not doing it.

What change I need to do to make the result looks like the below:

<td>123</td>
<td>456</td>

CodePudding user response:

You most likely need to use 10.0 as the key. Something like this.

 agg[3]["10.0"].value

But 10.0 is a weird key, although a valid one.

CodePudding user response:

I am assuming all the keys in the agg object are dynamic. Hence, you can try this :

const agg = {
  2: {
    values: 123
  },
  3: {
    values: {
      10: 456
    }
  }
};

const arr = [];

Object.keys(agg).forEach(key => {
  if (typeof agg[key].values === 'object') {
    Object.keys(agg[key].values).forEach(innerObjKey => {
        arr.push(agg[key].values[innerObjKey])
    })
  } else {
    arr.push(agg[key].values)
  }
});

console.log(arr);

  • Related