4

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.

3
  • To those down voting, is it the vagueness of my question? I wasn't sure of the right way to describe the difference in the file structure. Any info would be much appreciated to improve the quality. Commented Oct 9, 2015 at 12:24
  • stackoverflow.com/help/how-to-ask Did you Search and research before asking? Commented Oct 9, 2015 at 13:42
  • I did: I found similar questions but nothing that actually explained what the problem was. You're right though, in hindsight I should have been able to use them to resolve my own issue. Still, mark it as a duplicate if you believe it's been covered elsewhere. Commented Oct 9, 2015 at 14:16

1 Answer 1

8

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"}]

Sign up to request clarification or add additional context in comments.

1 Comment

This was great thanks. It was also the difference between an array and an array-like object that was tripping me up. Your map function made me realise what I was doing wrong overall.

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.