Jon Harding
Jon Harding

Reputation: 4946

Looping through object with one label

New to react and trying to loop through some data. I have an array of objects each object only has one property, another array. How can I reference key of "coins" and "bills" while looping through this data?

This comes from my container controller

const denominations = [
  {
    coins: [
      { name: 'Penny', namePlural: 'Pennies', label: '1¢', value: .01, },
      { name: 'Nickel', namePlural: 'Nickels', label: '5¢', value: .05, },
      { name: 'Dime', namePlural: 'Dimes', label: '10¢', value: .10, },
      { name: 'Quarter', namePlural: 'Quarters', label: '25¢', value: .25, }
    ]
  },
  {
    bills: [
      { name: 'Dollar', namePlural: 'Dollars', label: '$1', value: 1, },
      { name: 'Five', namePlural: 'Fives', label: '$5', value: 5, },
      { name: 'Ten', namePlural: 'Tens', label: '$10', value: 10, },
      { name: 'Twenty', namePlural: 'Twentys', label: '$20', value: 20, },
      { name: 'Fifty', namePlural: 'Fiftys', label: '$50', value: 50, },
      { name: 'Hundred', namePlural: 'Hundreds', label: '$100', value: 100, }
    ]
  }
];

This is inside the dumb controller.

let denoms = props.denominations.map(function (denom) {
    return (
        <div className="col" key={denom}>test</div>
    )
});

In Angular I'm used to the function (value, key) syntax. How can I extract the keys of 'coins' and 'bills'?

Upvotes: 0

Views: 23

Answers (1)

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

You can get the keys of your object using Object.keys method and use map again with returned array.

let denoms = props.denominations.map(function (denom) {
  return (
    Object.keys(denom).map(function(key){
      return (<div className="col" key={key}>test</div>)
    })
  );
});

if you want to get the value still you can access the value like this.

denom[key]

Edit:

If you want to loop through all of the objects within each key you can again use map with your value as follows.

let denoms = props.denominations.map(function (denom) {
  return (
    Object.keys(denom).map(function(key){
      return denom[key].map(function(item){
        return (<div className="col" key={item}>{item.name}</div>)
      })
    })
  );
});

Alternatively, you can use Object.values also if you don't care about keys

let denoms = props.denominations.map(function (denom) {
  return (
    Object.values(denom).map(function(value){
      return value.map(function(item){
        return (<div className="col" key={item}>{item.name}</div>)
      })
    })
  );
});

Upvotes: 3

Related Questions