![](/img/trans.png)
[英]Ramda js: lens for deeply nested objects with nested arrays of objects
[英]Merge two arrays with deeply nested key with Ramda
我最近開始使用Ramda處理來自JSONAPI的響應。 對於如何使用深層嵌套的鍵合並兩個對象,我有些困惑。
例如:
拿這兩組數據,
const users = [
{ id: 1,
attributes: {
firstName: "Bob",
lastName: "Lee"
},
relationships: {
phone: {
data: {
id: 2,
type: "phone"
}
}
},
type: "users"
},
{ id: 2,
attributes: {
firstName: "Kevin",
lastName: "Smith"
},
relationships: {
phone: {
data: {
id: 5,
type: "phone"
}
}
},
type: "users"
},
];
const phones= [
{ id: 2,
attributes: {
phoneNumber: "123-345-6789"
},
type: "phones"
},
{ id: 5,
attributes: {
phoneNumber: "987-654-4321"
},
type: "phones"
},
];
我要創建的是一個新陣列,將相關手機添加到用戶陣列中,並帶有一個包含所有相關對象的新鍵,如下所示:
const newUser =
[
{ id: 1,
attributes: {
firstName: "Bob",
lastName: "Lee"
},
relationships: {
phone: {
data: {
id: 2,
type: "phones"
}
}
},
included: {
phoneNumber: "123-345-6789"
}
},
{ id: 2,
attributes: {
firstName: "Kevin",
lastName: "Smith"
},
relationships: {
phone: {
data: {
id: 5,
type: "phones"
}
}
},
type: "users",
included: {
phoneNumber: "987-654-4321"
}
}
]
我嘗試了多種方法,例如map,pick和join,但是這些對象似乎並不想按照我希望的方式進行合並。 以下代碼將兩個對象放入同一數組中,但是我似乎無法將下一步繼續前進。
const data = R.pipe(
R.juxt([
R.pipe(R.path(['users'])),
R.pipe(R.path(['phones']))
]),
)
}),
這是我的第一種方法:
const {map, path, find, propEq, assoc} = R const addPhones = (phones, users) => map(user => { const phoneId = path(['relationships', 'phone', 'data', 'id'], user) const phone = find(propEq('id', phoneId), phones) return phone ? assoc('included', phone.attributes, user) : user }, users) const users = [{"attributes": {"firstName": "Bob", "lastName": "Lee"}, "id": 1, "relationships": {"phone": {"data": {"id": 2, "type": "phone"}}}, "type": "users"}, {"attributes": {"firstName": "Kevin", "lastName": "Smith"}, "id": 2, "relationships": {"phone": {"data": {"id": 5, "type": "phone"}}}, "type": "users"}, {"attributes": {"firstName": "Nancy", "lastName": "Johnson"}, "id": 3, "relationships": {"phone": {"data": {"id": 6, "type": "phone"}}}, "type": "users"}] const phones= [{"attributes": {"phoneNumber": "123-345-6789"}, "id": 2, "type": "phones"}, {"attributes": {"phoneNumber": "987-654-4321"}, "id": 5, "type": "phones"}, {"attributes": {"phoneNumber": "212-867-5309"}, "id": 7, "type": "phones"}] console.log(addPhones(phones, users))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
此版本適當處理了兩個列表中的缺失值。 如果存在沒有匹配電話的用戶,則該用戶將按原樣返回,沒有included
屬性。 如果有一部電話沒有匹配的用戶,則將其忽略。
這假定您可以在用戶中包括整個phone.attributes
對象。 如果您只需要包含phoneNumber
,則只需稍微復雜一點,用替換明顯的行即可
? assocPath(['included', 'phoneNumber'], phone.attributes.phoneNumber, user)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.