亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將嵌套數組映射到父對象的鍵值對中

將嵌套數組映射到父對象的鍵值對中

明月笑刀無情 2023-07-20 16:39:05
我有一個對象數組,如下所示:{    name: 'steve',    plaintiff:'IRS'    amount: 5000,    otherliens:[        {            amount:5000,            plaintiff:'irs'        },        {amount:5000,          plaintiff:'irs'        }    ]}我需要將其作為 csv 發送,因此我需要映射并迭代該子數組并將其展平為對象,如下所示:{    name:'steve',    plaintiff:'irs',    amount:5000,    plaintiff2:'irs',    amount2:5000,    plaintiff3:'irs',    amount3:5000}我通常用來執行此過程的代碼是將原始數組的內容映射到一個新數組中,arr.map(a,i =>{ a[i] ? a[i].amount = a[i].amount })  我可以通過平面猜測多個條目(請參閱電話和電子郵件)來處理基于字符串的子數組,因為如果我返回 null 它只是返回空白,這在 csv 中并不是最糟糕的事情。但我不能這樣做,因為訪問不存在的元素的子屬性顯然不起作用。這是我使用的地圖,其中 emailAddresses 是字符串數組,phoneNumbers 是字符串數組,otherliens 是對象數組。任何幫助將不勝感激并記住,因為它是批量數據傳輸和 csv,最后將有固定數量的列,我不介意空值,所以我想你會采用最長的子數組長度并在所有中使用它其他物體。
查看完整描述

1 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

使用循環從嵌套數組中分配屬性,而不是對項目數進行硬編碼。


我也不認為需要條件表達式。由于每個輸入元素都直接映射到輸出元素,因此不需要result[i]更新。


result = prospects.map(({fullName, firstName, lastName, deliveryAddress, city, state,zip4, county, plaintiff, amount, age, dob, ssn, otherliens, phones, emailAddresses}) => {

  let obj = {

    fullName: fullName,

    First_Name: firstName,

    Last_Name: lastName,

    Delivery_Address: deliveryAddress,

    City: city,

    State: state,

    Zip_4: zip4,

    County: county,

    plaintiff: plaintiff,

    Amount: amount,

    age: age,

    dob: dob,

    ssn: ssn

  };

  otherliens.forEach(({plaintiff, amount}, i) => {

    obj[`plaintiff${i+2}`] = plaintiff;

    obj[`amount${i+1}`] = amount;

  });

  phones.forEach((phone, i) => obj[`phone${i+1}`] = phone);

  emailAddresses.forEach((addr, i) => obj[`emailAddress${i+1}`] = addr);

  return obj;

})


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號