Javascript 如果条件匹配,则在对象数组中添加键

Javascript 如果条件匹配,则在对象数组中添加键,javascript,Javascript,我正在尝试根据条件获取对象数组。如果该值为true,则仅将该键和值添加到对象的新数组中 但是,它给出了错误: const arr=[{id:123,val:abcd',other:abcd},{id:123,val:abcd',other:abcd',show:true},{id:123,val:abcd',other:abcd',show:false},{id:123,val:abcd',other:abcd}] const newArr=arr.map(item=>({id:item.id

我正在尝试根据条件获取对象数组。如果该值为true,则仅将该键和值添加到对象的新数组中

但是,它给出了错误:

const arr=[{id:123,val:abcd',other:abcd},{id:123,val:abcd',other:abcd',show:true},{id:123,val:abcd',other:abcd',show:false},{id:123,val:abcd',other:abcd}]
const newArr=arr.map(item=>({id:item.id,val:item.val!=null?item.val:'}))

控制台日志(newArr)//它当前正在工作
,它在
数组中的一行上包含多个条件。map
函数无效

const arr=[{id:123,val:abcd',other:abcd},{id:123,val:abcd',other:abcd',show:true},{id:123,val:abcd',other:abcd',show:false},{id:123,val:abcd',other:abcd}]
const result=arr.map({id,val,show})=>{
常数newObj={
身份证件
val:val!=null?val:'
};
如果(显示){
newObj['show']=show;
}
返回newObj;
});
控制台日志(结果)那个

const arr=
[{id:123,val:'abcd',其他:'abcd'}
,{id:123,val:'abcd',其他:'abcd',show:true}
,{id:123,val:'abcd',其他:'abcd',show:false}
,{id:123,val:'abcd',其他:'abcd'}
] 
const newArr=arr.map({id,val,show})=>show?{id,val,show}:{id,val})
console.log(newArr)

。作为控制台包装{max height:100%!important;top:0;}
您可以这样重写它。 使用此语法,当
item.show
为true时,括号解析为and object,然后将其展开到对象中。 您还可以使用空合并来分配
item.val

 const expectedArr = arr.map((item) => ({
      id: item.id,
      val: item.val ?? "",
      ...(item.show && { show: item.show }),
    }));
const arr=[{id:123,val:abcd',other:abcd},{id:123,val:abcd',other:abcd',show:true},{id:123,val:abcd',other:abcd',show:false},{id:123,val:abcd',other:abcd}]
const expectedArr=arr.map(item=>({id:item.id,val:item.val?item.val:'',show:item.show?item.show:0}))
console.log(expectedArr)//解题
//但老实说,这是我能做的最远的你奇怪的代码golfed语法设置。。老实说,用什么?类似于if但不是if,更接近| |,但无论如何
log('跳过上面的内容,下面的关键时刻')
const theRealAnswer=arr.map(item=>{const i={id:item.id,val:item.val?item.val:'',show:item.show?item.show:0};if(!i.show){delete(i.show)}返回(i)})
console.log(TheeralAnswer)

//现在,逻辑结构(你给映射器的)不可能实现你想要的。编码不仅仅是语法,也是逻辑。您无法分配一个密钥来完全删除密钥本身
(show)和&(show:val.show)})应该是(item.show)和&(show:item.show)}@lissettdm抱歉,将
(item.show)和&(show:item.show)
更改为
…(item.show和&{show:item.show})
@Yousaf否该密钥也不起作用