Tuna Tuna - 1 month ago 7
Node.js Question

Javascript iterated inner values of Array/Object with the same key

Am building a nodejs app and it has very many clients with different timezones. I save all the data in Unix time stamp, when a client logs in i use the clients timezone to add or subtract to the unix time stamp stored in the database, so that it matches the clients time.

The user data (a document/object), has keys with Arrays and other objects aswell,

{
name: "data",
location": "us",
activity: [],
time: 1476301165252,
subdoc: [{
time: 1476301165252,
someotherKeys: ....
}]

}


How can i loop through this document and edit all the "time" keys(including inner objects and arrays aswell) and add or subtract a number to all "time" keys respectively.

The number will be uniform. meaning all the "time" keys will be iterated with the same number.

Answer

You'll want to use a recursive for...in loop to solve this, I think.

Something like this:

function changeTime (inputObj, newTimeVal) {
    var key;
    for (key in inputObj) {
        if (key === "time") {
            inputObj[key] = newTimeVal;
        }
        if (typeof inputObj[key] === 'object') {
            changeTime(inputObj[key], newTimeVal);
        }
    }
}

Might not be exactly right, but it should get you on the right path.

edit: If you only want to add or subtract from the original value, it's easy enough to use this same pattern:

function changeTime (inputObj, delta) { // we'll always add here-- you can pass in a negative or positive number to account for add or subtract
    var key;
    for (key in inputObj) {
        if (key === "time") {
            inputObj[key] = inputObj[key] + delta;
        }
        if (typeof inputObj[key] === 'object') {
            changeTime(inputObj[key], delta);
        }
    }
}