Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅在定义对象属性时映射对象属性(非空) 让我们考虑下一个数组: const arr = [ { name: "bob", age: 25, salary: 1000 }, { name: "bill", age: 32, salary: 1500 }, { name: "jake", age: 16, salary: null }, ]_Javascript - Fatal编程技术网

Javascript 仅在定义对象属性时映射对象属性(非空) 让我们考虑下一个数组: const arr = [ { name: "bob", age: 25, salary: 1000 }, { name: "bill", age: 32, salary: 1500 }, { name: "jake", age: 16, salary: null }, ]

Javascript 仅在定义对象属性时映射对象属性(非空) 让我们考虑下一个数组: const arr = [ { name: "bob", age: 25, salary: 1000 }, { name: "bill", age: 32, salary: 1500 }, { name: "jake", age: 16, salary: null }, ],javascript,Javascript,我需要将每个对象映射为下一个结构: firstName: string; personAge: string; grossSalary?: number; 所以 我需要映射person.salary,前提是原始对象中的null。否则,我需要省略它 我相信我与spread操作符非常接近,但是如果原始对象中的salary是null,我想我需要一个三元组来返回一个空对象。也许这种方法是错误的。。。idk不再…您可以检查薪资,并根据薪资返回对象: const arr=[ { 姓名:“鲍勃”, 年龄:

我需要将每个对象映射为下一个结构:

firstName: string;
personAge: string;
grossSalary?: number;
所以

我需要映射
person.salary
,前提是原始对象中的
null
。否则,我需要省略它


我相信我与spread操作符非常接近,但是如果原始对象中的salary是
null
,我想我需要一个三元组来返回一个空对象。也许这种方法是错误的。。。idk不再…

您可以检查薪资,并根据薪资返回对象:

const arr=[
{
姓名:“鲍勃”,
年龄:25岁,
工资:1000
},
{
姓名:“比尔”,
年龄:32岁,
工资:1500
},
{
姓名:“杰克”,
年龄:16岁,
薪金:空
},
]
const mappedArr=arr.map(person=>(
个人工资
?{firstName:person.name,personAge:person.age,grossalary:person.salary}
:{firstName:person.name,personAge:person.age}
)
);

console.log(mappedArr)
它需要类似于
…{person.salary===undefined?{}:{grossalary:person.salary}}
,因此如果它未定义,则传播一个空对象,不向父对象添加任何键,否则,传播一个带有
grossalary
的对象,将其作为父对象的键添加。
const mappedArr = arr.map(person => ({
 firstName: person.name,
 personAge: person.age,
 ...{grossSalary:
   person.salary
   ? person.salary
   : // I'm stuck :'((
   }
}))