niina
niina

Reputation: 119

How to refactor code for looping through array of objects using react?

i have array of objects with properties attributes and info...these attributes is an array of object with name and value pairs.

I have to display data available or not available based on these.

if the attributes name and value pairs are not empty and info property is defined for every attributes and info then i display message "data available" if not will display message "no data available".

Below is the data structure....

data: [
    {
        attributes: [
            {
                name: '', value: ''
            }, {
                name: '', value:
                    "somee"
            },
        ],
        info: 'ddd',
    },
    {
        attributes: [
            { name: '', value: '' },
        ],
        info: '',
    },
]

So i have tried something like below and works.

render = () => {
const has_attributes = this.data && 
    this.data.some((data) => data.attributes.length > 0 && 
        data.attributes.some(attribute => attribute.name || 
        attribute.value));
const has_info = this.data && this.data.some((data) => data.info);
    const has_some_data = has_attributes || has_info;
    return (
        {!this.data || !has_some_data) && 
            <div>No data available</div>}
        {this.data && has_some_data &&
            <div>Data available</div>}
    );
}

Could someone help me refactor something that's more readable and reduced code maybe.

Thanks.

Upvotes: 0

Views: 104

Answers (2)

Berouminum
Berouminum

Reputation: 530

Your variable naming doesn't follow typical javascript casing. In Javascript we use camelCase. First letter small, each following "word" starts with a big letter. Your are also double checking this.data. In addition splitting hasAttributes and hasInfo isn't necessary in your example since you only care if one of them is true anyway. This means you can merge them.

Consider using a linter like ESLint if you have trouble with your code style.

I'd say something like this might be more readable:

    const hasData = !!this.data && (
        this.data.some(data => data.info || (
            data.attributes.length > 0 &&
            data.attributes.some(attribute => attribute.name || attribute.value)
        ))
    );

    return (
        <div>
            {hasData ? 'Data available' : 'No data available'}
        </div>
    );

Upvotes: 1

KT-mongo
KT-mongo

Reputation: 2212

Your problem is your deeply nested structure and not how to refactor your code. With multiple nested arrays inherently your code will look "dirty" and there is only so much you can refactor. Consider restructuring your data object as anything you will try with your current structure will get harder to manage and maintain.

Upvotes: 1

Related Questions