Javascript根据对象中的另一个值向对象添加值

所以我有一个数组


data = [{time:100,id:1},

        {time:300,id:2},

        {time:150,id:3},

        {time:100,id:4}]

我想根据时间值向该数组中的每个对象添加另一个字段(状态),如果(时间 < 200),则该字段应指示为真,否则为假。所以新数组应该是这样的:


data = [{time:100,id:1,status:true},

        {time:300,id:2,status:false},

        {time:150,id:3,status:true},

        {time:100,id:4,status:true}]


慕标5832272
浏览 220回答 2
2回答

红颜莎娜

您可以简单地使用Array.prototype.map来实现:const data = [{&nbsp; &nbsp; time: 100,&nbsp; &nbsp; id: 1&nbsp; },&nbsp; {&nbsp; &nbsp; time: 300,&nbsp; &nbsp; id: 2&nbsp; },&nbsp; {&nbsp; &nbsp; time: 150,&nbsp; &nbsp; id: 3&nbsp; },&nbsp; {&nbsp; &nbsp; time: 100,&nbsp; &nbsp; id: 4&nbsp; }]console.log(data.map(el => ({ ...el,&nbsp; status: el.time > 200})));

千巷猫影

您可以使用map(). return来自回调的新对象,其中包含所有以前的道具和一个新道具stautsconst data = [{time:100,id:1},&nbsp; &nbsp; &nbsp; &nbsp; {time:300,id:2},&nbsp; &nbsp; &nbsp; &nbsp; {time:150,id:3},&nbsp; &nbsp; &nbsp; &nbsp; {time:100,id:4}]&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;const res = data.map(x => ({...x,status:x.time < 200}));console.log(res)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript