Pavel
Pavel

Reputation: 2101

JS reduce loses first element of array

I have a reduce function for reducing and formatting object keys and values to string in format key1=value1\nkey2=value2, but it is losing first element:

Sample data

{
  "key1": "value1",
  "key2": "value2"
}
private toMt5Set(data: any): string {
 const object = JSON.parse(data);
   return Object.keys(object || {})
          .reduce((acc, key) => acc + `${key}=${object[key]}\n`);
}

Upvotes: 2

Views: 803

Answers (2)

terrymorse
terrymorse

Reputation: 7086

If I may, I'd like to recommend a small style improvement.

Your reduce function (with the '' initializer added):

.reduce((acc, key) => acc + `${key}=${object[key]}\n`, '');

is accessing object, which is defined outside the scope of reduce. These "outside of function" references are more difficult to reason about than "inside function" references.

You can avoid this "outside of function" issue by replacing your call to Object.keys() (which returns key) with Object.entries() (which returns key, value).

The "all within scope" version looks like this:

Object.entries(object || {})
  .reduce((acc, [key, val]) => acc + `${key}=${val}\n`, '');

It's a small change, but it makes the code a bit easier to understand.

Upvotes: 4

Alkis Kalogeris
Alkis Kalogeris

Reputation: 17745

Try adding the initial value of acc

Object.keys(object || {}) .reduce((acc, key) => `${acc}${key}=${object[key]}\n`, '');

Output

key1=value1\nkey2=value2\n

Upvotes: 3

Related Questions