Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an object's keys to make JSON easier to handle in React

If I have this JSON:

{
    'name': 'Active user',
    'config': {
        'status': 'active',
    }
},
{
    'name': 'Paused user',
    'config': {
        'status': 'active',
    }
}

Then I can render a React component and access the data easily:

render: function() {
    var panels = [];

    this.props.accounts.forEach(function(account) {
        panels.push(
            <Tabs.Panel title={account.name}>
                <h2>{account.name}</h2>
            </Tabs.Panel>
        );
    });

    return (<Tabs>{panels}</Tabs>);
}
...
React.render(<Tabs accounts={ACCOUNTS} />, document.body);

If my JSON is structured as below instead, how should I re-factor the render function to work as I want?

{
    'Active User': {
        'config': {
            'status': 'active',
        }
    },
    'Paused User': {
        'config': {
            'status': 'paused',
        }
    }
}

i.e. I no longer have a name attribute to display.

like image 746
CherryFlavourPez Avatar asked Feb 08 '23 20:02

CherryFlavourPez


1 Answers

Is this what you want?

var users = {
    'Active User': {
        'config': {
            'status': 'active',
        }
    },
    'Paused User': {
        'config': {
            'status': 'paused',
        }
    }
};

var usersWithName = Object.keys(users).map(function(key) {
  var user = users[key];
  user.name = key;
  return user;
});

Where usersWithName = [{"config":{"status":"active"},"name":"Active User"},{"config":{"status":"paused"},"name":"Paused User"}]

like image 97
Samuli Hakoniemi Avatar answered Feb 11 '23 11:02

Samuli Hakoniemi