Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping unknown items count in Javascript object

I am parsing a data source and want to populate an object in JS to end up somehting like this:

data = {
    "USA":
        {"NY":{"active":5,"inactive":2}},
        {"WA":{"active":16,"inactive":11}},
    "Canada":
        {"NY":{"active":5,"inactive":2}}
}

In the beginning I do not know the number of countries or states I will get data for. So I start like this:

var data = {}

Then try to populate data like this:

data["USA"]["NY"]["active"] = data["USA"]["NY"]["active"]++;

But it does not work.

like image 505
Kashif Avatar asked Jul 20 '26 06:07

Kashif


1 Answers

You need for every level of the object a check and if not set, then take either an object as default or for number, zero.

var data = {};

data["USA"] = data["USA"] || {};
data["USA"]["NY"] = data["USA"]["NY"] || {};
data["USA"]["NY"]["active"] = data["USA"]["NY"]["active"] || 0;
data["USA"]["NY"]["active"]++;

console.log(data);

A better approach is to use a function for checking and making a default object

function getValue(o, path) {
    return path.reduce(function (o, k) {
        return (o || {})[k];
    }, o);
}

function setValue(object, path, value) {
    var way = path.slice(),
        last = way.pop();

    way.reduce(function (r, a) {
        return r[a] = r[a] || {};
    }, object)[last] = value;
}

function increment(object, path, value) {
    setValue(data, path, (getValue(data, path) || 0 ) + (value || 1));
}

var data = {};
increment(data, ['USA', 'NY', 'active'], 1);

console.log(data);
like image 58
Nina Scholz Avatar answered Jul 21 '26 23:07

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!