如何使用地图功能更改对象数组的值?

问题描述 投票:-1回答:1

我需要通过更改属性值来获取整个数组数据。但是map仅返回更改后的值。有什么办法吗?

输入:[{id: 527, status: 0},{id: 528, status: 0},{id: 529, status: 0},{id: 530, status: 0}]

必选操作:[{id: 527, status: 1},{id: 528, status: 0},{id: 529, status: 0},{id: 530, status: 0}]

testDetails = testDetails
    .map((values)=> values.id == '527' ? values.status = 1&&values : values)

output :[0,{id: 528, status: 0},{id: 529, status: 0},{id: 530, status: 0}]
javascript arrays object
1个回答
2
投票
您可以为所需的ID取一个状态不同的新对象。这种方法不会变异原始数据。

var data = [{ id: 527, contractor_id: 1138, role_type: "specific", passpercent_max: 100, failpercent_min: 0 }, { id: 529, contractor_id: 1138, role_type: null, passpercent_max: null, failpercent_min: null }, { id: 530, contractor_id: 1138, role_type: null, passpercent_max: null, failpercent_min: null }, { id: 531, contractor_id: 1138, role_type: null, passpercent_max: null, failpercent_min: null }], result = data.map(o => o.id === 527 ? { ...o, status: 1 } : o); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.