简体   繁体   中英

I am trying to add an element to a js object

I try to push key value pairs to an object. the key value pairs have to be added to a certain index which is given by the e.vatRecord.debit . This variable is working properly if I log this on console. But in combination it does not work.

journalByAccounts = {}; // define an object
  data.entries.forEach(function(e) {
    journalByAccounts[e.vatRecord.debit].push({
      valuta: e.valuta,
      text: e.text,
      debit: e.mainRecord.amount
    });
  });

Either you first need to initialize the object journalByAccounts[e.vatRecord.debit] to an empty array [] because you can't push into undefined (expecting that it magically becomes an array):

journalByAccounts = {};
data.entries.forEach(function(e) {
    if (!journalByAccounts[e.vatRecord.debit])
        journalByAccounts[e.vatRecord.debit] = [];

    journalByAccounts[e.vatRecord.debit].push({
        valuta: e.valuta,
        text: e.text,
        debit: e.mainRecord.amount
    });
});

The if is being done to make sure that it still goes right if e.vatRecord.debit can contain the same value more than once, creating the array only once for each value.

Or if you don't actually want an array, then you should do an assignment:

journalByAccounts[e.vatRecord.debit] = {
  valuta: e.valuta,
  text: e.text,
  debit: e.mainRecord.amount
};
journalByAccounts = []; // define an object

you must define an empty array, not an obj.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM