Get the Flavors: Solution Review
Solution review.
We’ll cover the following
So a given employee’s JSON is shaped like this
{
"name": "Devante",
"username": "Devante40",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg",
"email": "Devante40_Trantow11@yahoo.com",
"dob": "1958-06-01T03:53:42.127Z",
"phone": "544.986.5264",
"address": {
"street": "Louie Mission",
"suite": "Suite 504",
"city": "Lake Kyle",
"zipcode": "60316",
"geo": {
"lat": "-65.8775",
"lng": "-66.4677"
}
},
"website": "delaney.info",
"company": {
"name": "Keeling Group",
"catchPhrase": "Self-enabling grid-enabled architecture",
"bs": "real-time orchestrate interfaces"
},
"interests": {
"foods": {
"sweets": {
"iceCream": {
"favoriteFlavor": "White Chocolate Raspberry Truffle"
}
}
}
}
}
And their flavor’s tucked away here
"interests": {
"foods": {
"sweets": {
"iceCream": {
"favoriteFlavor": "White Chocolate Raspberry Truffle"
}
}
}
}
index.js
import { path } from 'ramda';
import data from './data.json';
const getFlavor = path([
'interests',
'foods',
'sweets',
'iceCream',
'favoriteFlavor'
]);
const result = getFlavor(data);
console.log({ result });
{ result: 'White Chocolate Raspberry Truffle' }
data.json
{
"interests": {
"foods": {
"sweets": {
"iceCream": {
"favoriteFlavor": "White Chocolate Raspberry Truffle"
}
}
}
}
}
Our solution must use lenses, so this can easily become a lensPath and view combination.
我们的解决方案必须使用镜头,因此这很容易成为镜头和视图的组合。
import { lensPath, view } from 'ramda';
import data from './data.json';
const favoriteFlavor = lensPath([
'interests',
'foods',
'sweets',
'iceCream',
'favoriteFlavor'
]);
const result = view(favoriteFlavor, data);
console.log({ result });
But this only works for one person! Using it on a list of people returns undefined because your using view on the array.
但这只适用于一个人!在人员列表上使用它将返回未定义,因为您在数组上使用视图。
How do we generalize a solution to a list?
Map #
import { lensPath, map, view } from 'ramda';
import employees from './employees.json';
const favoriteFlavor = lensPath([
'interests',
'foods',
'sweets',
'iceCream',
'favoriteFlavor'
]);
const result = map(view(favoriteFlavor), employees);
console.log({ result });
As we previously discussed, lenses use map themselves. When they receive the data, they begin unfolding and traverse the data structure.
Adding map on top of that just loops through employees and feeds each one to view as data.
Our result is an array of everyone’s favorite flavor!
如前所述,镜头本身使用map。当他们收到数据时,他们开始展开并遍历数据结构。 在上面添加映射只是循环遍历员工,并将每个员工作为数据进行查看。 我们的结果是一系列大家最喜欢的口味!