2

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`);
}
2
  • Please give sample input data. Commented May 9, 2020 at 17:10
  • 1
    reduce((acc, key) => acc + ${key}=${object[key]}\n,""); give initial value Commented May 9, 2020 at 17:11

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Try adding the initial value of acc

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

Output

key1=value1\nkey2=value2\n

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.