Search code examples
javascriptjavascript-objects

Imputing zero values in nested object in Javascript


I have a nested object similar to this structure:

data = {1950: {A:1, B:2, C:3, D:4},
        1960: {A:1, B:2, D:4, E:5},
        1970: {B:2, C:3, D:4, E:5},
        1980: {C:3, E:5}}

I'm struggling with how to impute zeros for the missing letter key/pairs so that the object is no longer ragged. Does anyone have any ideas of how i can iterate through and fill in the missing values?


Solution

  • You can use Object.keys() to iterate on each key and fill the missing key from a defaultObject using Object.assign().

    const data = {1950: {A:1, B:2, C:3, D:4}, 1960: {A:1, B:2, D:4, E:5}, 1970: {B:2, C:3, D:4, E:5}, 1980: {C:3, E:5}},
          defaultObject = {A:0, B:0, C:0, D:0, E:0},
          result = Object.keys(data).reduce((r,k) => {
            r[k] = Object.assign({}, defaultObject, data[k]);
            return r;
          },{});
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }