为了账号安全,请及时绑定邮箱和手机立即绑定

将嵌套数组映射到父对象的键值对中

将嵌套数组映射到父对象的键值对中

明月笑刀无情 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 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信