1

I have an array of objects, where each object has a "standings" property (example data below). I want to flatten the standings array and add it to the end of the parent object.

[{
name: "Entry 1",
value: 0,
standings: [{
    week: 1,
    team: 'MIN'
    }, {
    week: 2,
    team: 'NE'
    }, {
    week: 3,
    team: null
    }]
}, {
name: "my Other Entry",
value: 3,
standings: [{
    week: 1,
    team: 'BUF'
    }, {
    week: 2,
    team: 'CIN'
    }, {
    week: 3,
    team: 'TB'
    }]
}];

How can I get:

[{name: "Entry 1", value: 0, w1: 'MIN', w2: 'NE', w3: null},
{name: "my Other Entry", value: 3, w1: 'BUF', w2: 'CIN', w3: 'TB'}]

I was thinking some variation of flatten?

1
  • 1
    Do you want to do it programmatically in javascript? Or you are looking for suggestions to name your flat json? Commented Sep 10, 2015 at 17:30

2 Answers 2

1

A Array.prototype.reduce will do:

var data = [
        {
            name: "Entry 1",
            value: 0,
            standings: [{
                week: 1,
                team: 'MIN'
            }, {
                week: 2,
                team: 'NE'
            }, {
                week: 3,
                team: null
            }]
        }, {
            name: "my Other Entry",
            value: 3,
            standings: [{
                week: 1,
                team: 'BUF'
            }, {
                week: 2,
                team: 'CIN'
            }, {
                week: 3,
                team: 'TB'
            }]
        }
    ],
    data1 = data.reduce(function (r, a) {
        r.push(a.standings.reduce(function (rr, b) {
            rr['w' + b.week] = b.team;
            return rr;
        }, {
            name: a.name,
            value: a.value
        }));
        return r;
    }, []);
document.write('<pre>'+JSON.stringify(data1, 0, 4)+'</pre>');

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

Comments

1

I don't think _.flatten will help much here considering your data structure.

Without the use of a library you can just loop over your data and convert it manually:

function collapseStandings() {
    var formattedData = [];
    data.forEach(function(entry) { // data is your sample data.
        var convertedObj = {
            name: entry.name,
            value: entry.value
        };
        entry.standings.forEach(function(standing){
            convertedObj['w' + standing.week] = standing.team;
        });

        formattedData.push(convertedObj);                   
    });

    return formattedData;
}

Complete fiddle.

Comments

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.