Frage

Can someone explain how to iterate over all of an object's key-val pairs? Do I need to add the stringified pairs into a new object, then return that object? So far, I've got the following, which works for nested objects, but it'll only return the first pair.

var objectify = function (obj, stringifyJSON) {
        for (var key in obj) {
            if (obj.hasOwnProperty) {
                return (stringifyJSON(key) + ":" + stringifyJSON(obj[key]));
            }

As it is, for an object like {"a": 1, "b": 2, "c":3 }, I'm getting back just {"a": 1}.

I've also tried the following:

var objectify = function (obj, stringify) {
    var holder = {};
        for (var key in obj) {
            if (obj.hasOwnProperty) {
                holder[stringifyJSON(key)] = stringifyJSON(obj[key]);
            }
        }
        return ("" + holder + "");
    };

which just returns {[object Object]}. I've tried assigning the key and value with quotes and without calling stringify on the key and value, but those both return {[object Object]} as well.

Here's the snippet that calls objectify:

else if (typeof obj === "object" && obj !== null) {
    return ("{" + objectify(obj, stringifyJSON) + "}");
}
War es hilfreich?

Lösung

Don't use return in the loop. A possible solution could be:

var objectify = function (obj, stringifyJSON) {
     var tmp = '';
        for (var key in obj) {
            if (obj.hasOwnProperty) {
                tmp  = tmp + (stringifyJSON(key) + ":" + stringifyJSON(obj[key]));
                tmp =+ '; '; // here you can put any char that you want to separate objects
            }
        }
        return tmp;
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top