2
votes

I have a function like this:

const jsonObject = {a: {b: 'c'}};
const x = 'a.b';
const properties = x.split('.');

const item = properties.reduce((obj, prop) => obj && obj[prop], jsonObject);

console.log(item); // prints 'c;

This function, dynamically traverses the jsonObject and prints the value.

This works fine, but this style of declaration doesn't support my environment. So I wan trying to convert this to function style declaration something like this:

const item = properties.reduce(function(obj, prop){
   if(obj && obj[prop]) return obj[prop];
});

But this doesn't seems to be working. Its printing (item) undefined.

6
Simply return the expression, you don't need the if statement.ryeballar
Thank you everyone.. i randomly choose one answer and upvoted all correct answers. Thanks a lot again.kaounKaoun

6 Answers

1
votes

Working Snippet

const jsonObject = {
  a: {
    b: 'c'
  }
};
const x = 'a.b';
const properties = x.split('.');

const item = properties.reduce(function(obj, prop) {
  return obj && obj[prop];
}, jsonObject);

console.log(item); // prints 'c;

Explanation

  1. Fat arrow (=>) returns anything written on the right side by default (i.e. without a block as a body)
  2. While porting to a function expression or declaration, we need to explicitly use the return keyword.
3
votes
const item = properties.reduce((obj, prop) => obj && obj[prop], jsonObject);

Is similar to

const item = properties.reduce(function(obj, prop){
   return obj && obj[prop];
}, jsonObject);

Read more about .reduce and its arguments here

1
votes

Yes, the correct translation would be:

function(obj, prop) {
    return obj && obj[prop];
}
1
votes

In your code:

const item = properties.reduce(function(obj, prop){
  if(obj && obj[prop]) return obj[prop];
});

You are never passing the jsonObject in as the second parameter to the function, so .reduce doesn't know what to enumerate on. The correct way of doing it is:

const item = properties.reduce(function(obj, prop){
  if(obj && obj[prop]) return obj[prop];
}, jsonObject);
1
votes

An awesome online tool BabelJs

It can help you with converting your ES6 to ES5 without much effort. However I recommend understanding how its doing the conversion

   'use strict';

    var jsonObject = { a: { b: 'c' } };
    var x = 'a.b';
    var properties = x.split('.');

    var item = properties.reduce(function (obj, prop) {
      return obj && obj[prop];
    }, jsonObject);

    console.log(item);
1
votes

You may add a default value for preventing a not given property in the object.

const item = properties.reduce(function (obj, prop){
        return (obj || {})[prop];
    }, jsonObject);