如何为数组对象添加嵌套details计数作为person_number字段
给数组每个对象添加对应details数组长度的person_number字段
你当前代码的问题在于,给person_number赋值时用了data.map(x=>x.details.length),这会生成一个包含所有对象details长度的数组,而非当前遍历对象自身的details长度。
错误代码分析
const arrWithCount = data.map(object => { return {...object, person_number: data.map(x=>x.details.length)}; });
这段代码会让每个对象的person_number变成类似[2,1,1,1]这样的数组,而不是单个数字。
正确实现方案
只需要在遍历每个对象时,直接取当前对象的details.length作为person_number的值即可,同时用对象扩展运算符保留原对象属性,避免修改原数据:
// 处理data数组 const newData = data.map(item => { return { ...item, person_number: item.details.length }; }); // 同理处理name数组 const newName = name.map(item => { return { ...item, person_number: item.details.length }; }); console.log("处理后的data数组:", newData); console.log("处理后的name数组:", newName);
处理后示例结构
单个对象的输出示例:
{ id: 222222, document_file_name: "4020653_FileName.pdf", document_updated_at: "2020-07-08T19:41:28.385Z", document_type_label: "something", state: "accepted", person_number: 2, // 对应自身details数组的元素数量 details: [ { /* 第一个details元素 */ }, { /* 第二个details元素 */ } ] }
内容的提问来源于stack exchange,提问作者Whoopcg
相关产品推荐
相关产品推荐

