skip to Main Content

I have the following JS code:

var expected_dict = {}
  for (var i = 1; i < expected_data.length; i++) {
    if (expected_data[expected_data[i][0]] == undefined) {
      expected_dict[expected_data[i][0]] = {}
    }
    expected_dict[expected_data[i][0]][expected_data[i][20]] = {}
    expected_dict[expected_data[i][0]][expected_data[i][20]] = expected_data[i][21]
    console.log(expected_dict)
  }

expected_data is an array of arrays, like

[
    ['revisionid1', ..., 'code1', 'cp1']
    ['revisionid1', ..., 'code2', 'cp2']
]

I’d expect the code to add values to the expected_dict revisionid key, but the output ends up being

{ 'revisionid1': { 'code1': 'cp1' } }
{ 'revisionid1': { 'code2': 'cp2' } }

Which means it looks like it’s overwriting the dict each time.
What I want would be

{ 'revisionid1': { 'code1': 'cp1', 'code2': 'cp2'} }

Is there something I’m not understanding about how JS handles dicts?

2

Answers


  1. Try this

    var expected_dict = {};
    
    for (var i = 0; i < expected_data.length; i++) {
      var revisionId = expected_data[i][0];
      var code = expected_data[i][20];
      var cp = expected_data[i][21];
    
      if (!expected_dict[revisionId]) {
        expected_dict[revisionId] = {}; // Create the inner dictionary if it doesn't exist
      }
    
      expected_dict[revisionId][code] = cp; // Set the key-value pair in the inner dictionary
    }
    
    console.log(expected_dict);
    Login or Signup to reply.
  2. Reduce the data to a dict, with the first element as a dict key, the remaining items act as key/value pairs for a dict element:

    const expected_dict = expected_data.reduce((r, item) => 
      item.forEach((v, i) => i && (i + 1)%2 && ((r[item[0]] ??= {})[item[i - 1]] = v)) || r, {});
    
    console.log(expected_dict);
    <script>
    const expected_data = [
        ['revisionid1', 'code1', 'cp1'],
        ['revisionid1', 'code2', 'cp2']
    ];
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search