Using a query to transform data from data & changeSet

I want to define a changeable variable and merge table.changeSet into table.data. The main goal is: change only changed JSON fields and then save to database.

I have categoriesTable that contains two fields: name and weight. Then I save these data in JSONB format in my PostgreSQL database.

For example, the categoriesTable.data is [{"name": "nature", "weight": 0.8}, {"name": "climbing", "weight": 0.8}]. Then I changed the second record weight with name climbing from 0.8 to 0.82 in the categoriesTable and in result got categoriesTable.changeSet image . But when I'm trying to execute the next query:

// Reference external variables with curly brackets or using JS variables
var data = categoriesTable.data;
const changeset = categoriesTable.changeSet;

changeset.forEach(function(change) {
  for (var key in change) {
      var index = key.toString();
      if (data[index]) {
          Object.assign(data[index][key], change[key]);
      } else {
          data[index] = change[key];
      }
  }
});

return data;

I got `message:"changeset.forEach is not a function"`

The chageSet property is an object and not an array so you would have to probably start with an Object.keys(changeset) type of thing and the loop using the key values (which are, I believe, the row ids from the table).

Also, is this a legacy table?

I believe the new tables have a changeSetArray and a changeSetObject property and my response about the row ids being the key names for the object are specifically about these properties on the new table.

1 Like

Thanks @pyrrho! Agreed that Object.keys (or Object.entries) is helpful here since you'll need an array :white_check_mark:

For the legacy table, we have a code example here that shows how to merge the changeSet with the table data using Object.entries.

1 Like