Skip to content
Advertisement

Dynamically add empty index to array based on default indexes

I have below array, which includes a set of default indexes, that must be present in my final array:

JavaScript

The above array is saved in a variable called $entities.

Now, I have a 3rd party API, that will return the above entities, but only include them in the response if the entity contains a value.

For example, a $response can look like this:

JavaScript

As you can see, if comparing the returned array with the indexes that I expect, there is a few missing:

  • deliveredAt
  • totals.due, totals.gross, totals.net, totals.tax.amount, totals.tax.net, totals.tax.rate

I am trying to make a method that can iterate over the $response array, and check if it contains the indexes that I expect. If not, I simply want to set the index with a value of null.

Below is what I have so far:

JavaScript

However, this will only add an index that is not an array. In this example, it will only add: deliveredAt => null.

How can I do, so the above method can iterate through multiple at least 2 nested arrays and add the index name and null value?

Advertisement

Answer

You can define initial array with keys and NULL (or whatever you need) as values:

JavaScript

Fiddle.

Also note that keys from $realData that do not exist in $entities will be added to result.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement