[英]Javascript ES6 split object array into two different object subarrays
[英]Es6 - Match two different object keys with different name
我正在處理兩個我無權更改其字段名稱的 API(示例如下)
const api1 = {
studentId: 'abc',
studentName: 'John Doe',
studentAge: 19,
course: 'Engineering',
}
const api2 = {
id,
personalInfo: {
name,
age
},
course:
}
基本上我需要將數據從 api2 傳輸到 api 1 所以我所做的是:
const payload = {}
payload["studentId"] = api2.id,
payload["studentName"] = api2.personalInfo.name,
payload["studentAge"] = api2.personalInfo.age,
payload["course"] = api2.course,
有沒有辦法如何動態地做到這一點?
您可以采用一個包裝器對象,它將給定 API 的所有想要的屬性包裝到一個新的 API 中。
這種方法采用一個對象,通過獲取對象的條目並迭代這些條目,直到找到非對象,然后將值分配給新對象,從而將給定的屬性映射到所需結構的新格式/名稱。 如果找到一個對象,它將獲取這個對象並從嵌套對象中獲取值。
如果提供了嵌套的目標屬性,例如
{ studentName: 'personalInfo.name' }
(例如從 API1 創建 API2)您需要拆分值並創建一個具有嵌套結構的對象,例如
const
path = value.split('.'),
last = path.pop();
path.reduce((o, k) => o[k] ??= {}, target)[last] = source[key];
在else
部分。
const assign = (source, wrapper, target = {}) => { Object.entries(wrapper).forEach(([key, value]) => { if (value && typeof value === 'object') assign(source[key], value, target); else target[value] = source[key]; }); return target; }, api1 = { studentId: 'abc', studentName: 'John Doe', studentAge: 19, course: 'Engineering' }, api2 = { id: 'someId', personalInfo: { name: 'someName', age: 'someAge' }, course: 'someCourse' }, wrapper = { id: 'studentId', personalInfo: { name: 'studentName', age: 'studentAge' }, course: 'course' }, payload = assign(api2, wrapper); console.log(payload);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.