在使用reduce时突然发现reduce似乎可以遍历对象嵌套结构
function getObjectPropertyValue(obj, propertyPath) {
return propertyPath.split('.').reduce((result, key) => result[key], obj);
}
const person = {
name: 'John',
address: {
city: 'New York',
street: '123 ABC Street'
}
};
const name = getObjectPropertyValue(person, 'name');
console.log(name); // John
const city = getObjectPropertyValue(person, 'address.city');
console.log(city); // New York
const street = getObjectPropertyValue(person, 'address.street');
console.log(street); // 123 ABC Street
查询文档:Array methods
reduce/reduceRight
When we need to iterate over an array – we can use forEach, for or for..of.
When we need to iterate and return the data for each element – we can use map.
The methods

最低0.47元/天 解锁文章
455

被折叠的 条评论
为什么被折叠?



