Javascript 基于数组编辑对象中的多个值

Javascript 基于数组编辑对象中的多个值,javascript,Javascript,假设我有: const fixed = {pear: 100, apple: 4} const arr = [ {name: 'P1', pear: 150, apple: 2}, {name: 'P2', pear: 50, apple: 5}, {name: 'P3', pear: 450, apple: 1}, {name: 'P4', pear: 100, apple: 3}, ] 我想要: const result = [ {name: 'P1', pear: -

假设我有:

const fixed = {pear: 100, apple: 4}
const arr = [
  {name: 'P1', pear: 150, apple: 2},
  {name: 'P2', pear: 50, apple: 5},
  {name: 'P3', pear: 450, apple: 1},
  {name: 'P4', pear: 100, apple: 3},
]
我想要:

const result = [
  {name: 'P1', pear: -50, apple: 2},
  {name: 'P2', pear: 50, apple: -1},
  {name: 'P3', pear: -350, apple: 3},
  {name: 'P4', pear: 0, apple: 1},
]
因此,
result
具有与
arr
相同的项目,但具有基于
固定的
对象值编辑的
apple
pear

新的
pear
(和
apple
)值应该是
fixed.pear-oldPearValue
,例如,对于
arr[0]

fixed.pear - arr[0].pear = 100 - 150 = -50 --> result[0].pear = -50
以下是我尝试过的:

功能差异(固定值){
返回值-固定
}
const fixed={pear:100,apple:4}
常数arr=[
{名称:'P1',梨:150,苹果:2},
{名称:'P2',梨:50,苹果:5},
{名称:'P3',梨:450,苹果:1},
{名称:'P4',梨:100,苹果:3},
]
常量数据集=arr.flatMap((d)=>{
Object.entries(固定).forEach(([key,value])=>{
返回{…d[key]:差(值,d[key])}
})
})

log(数据集)
您可以获取条目并映射新属性

const
固定={pear:100,apple:4},
arr=[{name:'P1',pear:150,apple:2},{name:'P2',pear:50,apple:5},{name:'P3',pear:450,apple:1},{name:'P4',pear:100,apple:3}],
dataset=arr.map(d=>({…d,…Object.fromEntries(Object
.参赛作品(固定)
.map(([k,v])=>[k,v-d[k]]
) }));
console.log(数据集)

.as控制台包装{max height:100%!important;top:0;}
如果固定对象必须是具有相同字段的固定对象,则可以尝试此操作
const fixed={pear:100,apple:4};
常数arr=[
{名称:'P1',梨:150,苹果:2},
{名称:'P2',梨:50,苹果:5},
{名称:'P3',梨:450,苹果:1},
{名称:'P4',梨:100,苹果:3}
];
让数据=arr.map((项目)=>{
返回{…项,pear:fixed.pear-item.pear,apple:fixed.apple-item.apple};
});

console.log('checkk',数据)
因为不必要的
.flatMap()
调用的回调不会返回任何
.return…
中。forEach()
回调不会执行任何操作。