0

In this object-array, there could (!) be structure mistakes like shown below, which I need to get corrected. As you can see, data should be an array with objcts. Sometimes it is an object, which has an object. In this example the last element of group has the field "1", which is wrong. This field name could have different names. I need to remove that.

{
    "group" : [
        {
            "title" : "title 1",
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        },
        {
            "data" : {  // <-- should be array
                "1" : { // <-- wrong
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            }
        }
    ]
}

The result should be:

{
    "group" : [
        {
            "title" : "title 1",
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        },
        {
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        }
    ]
}
2
  • Where is the code that creates this object ? Commented Jan 9, 2016 at 18:37
  • It does not look like a hard problem. Why haven't you tried yourself? Commented Jan 9, 2016 at 18:37

1 Answer 1

1

var data = {
    "group" : [{
            "title" : "title 1",
            "data" : [
                { "field 1" : "Lorem ipsum" }
            ]
        }, {
            "data" : {
                "1" : { "field 1" : "Lorem ipsum" }
            }
        }
    ]
};

// check each group
data.group.forEach(function (g) {
    // is it an array (simple check for "length" property)
    if (typeof g.data.length === "undefined") {
        // if not, convert "data" to an array and replace it in-place
        g.data = Object.keys(g.data).map(function (d) {
                return g.data[d];
            })
    }
});

console.log(JSON.stringify(data));

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

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.