Trim object info in Javascript

Use this method to trim JS object values and display only the required info (which I do a lot for deugging purposes). Here is what gives me a concise info I am looking for while debugging my code in JS.

function trimInfoInArray(array, props) {
    return array.map(function (item) {
        var obj = {};
        for (var i = 0, len = props.length; i < len; i++)
            obj[props[i]] = item[props[i]];
        return obj;
    });
}

function trimInfoInObject(object, props) {
    var obj = {};
    for (var i = 0, len = props.length; i < len; i++)
        obj[props[i]] = object[props[i]];
    return obj;
}

Now the example on how to use it is as following

var player1 = {id: 1, name:'Tom', Age: 30}
var player2 = {id: 2, name:'Jon', Age: 28}
var players = [player1, player2]
console.log(JSON.stringify(trimInfoInArray(players, ["id", "name"])));
console.log(JSON.stringify(trimInfoInObject(player1, ["id", "name"])));

With some objects having hundreds of properties and printing those values and searching for just the right info is an easy task with these functions.


Leave A Comment

Your email address will not be published.