问题
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.
回答1:
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
- Fat arrow (=>) returns anything written on the right side by default (i.e. without a block as a body)
- While porting to a function expression or declaration, we need to explicitly use the
return
keyword.
回答2:
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
回答3:
Yes, the correct translation would be:
function(obj, prop) {
return obj && obj[prop];
}
回答4:
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);
回答5:
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);
回答6:
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);
来源:https://stackoverflow.com/questions/49074757/converting-an-arrow-style-function-to-function-style