我有以下示例数组
let myArray = [
{name: "Sam", status: 'not_started', progress: 'start'},
{name: "Sara", status: 'not_started', progress: 'start'},
{name: "John", status: 'not_started', progress: 'start'},
{name: "Eric", status: 'not_started', progress: 'start'}
]
如果所有元素的状态都是:“not_started”,那么我想将第一个元素的进度更新为“start”,其余元素更新为“lock”。所以数组看起来像这样:
let myArray = [
{name: "Sam", status: 'not_started', progress: 'start'},
{name: "Sara", status: 'not_started', progress: 'lock'},
{name: "John", status: 'not_started', progress: 'lock'},
{name: "Eric", status: 'not_started', progress: 'lock'}
]
如果第一个元素的状态为“已完成”,那么第二个元素的状态为“开始”,其余元素的状态为“锁定”,如下所示
let myArray = [
{name: "Sam", status: 'completed', progress: 'completed'},
{name: "Sara", status: 'not_started', progress: 'start'},
{name: "John", status: 'not_started', progress: 'lock'},
{name: "Eric", status: 'not_started', progress: 'lock'}
]
此外,如果前两个“已完成”,那么它会如下所示
let myArray = [
{name: "Sam", status: 'completed', progress: 'completed'},
{name: "Sara", status: 'completed', progress: 'completed'},
{name: "John", status: 'not_started', progress: 'start'},
{name: "Eric", status: 'not_started', progress: 'lock'}
]
我尝试映射
myArray 并创建状态和进度值的数组,并根据状态progress: array[status]
获取进度值,但这不会更新进度:'lock' 正确,因为 'not_started' 可以有进度:'start' 或 'lock'
显然我需要根据前一个的值更新下一个,但我还没有得到这一点。
有谁知道我怎样才能实现这个目标?
谢谢
最佳答案
您可以使用 map()
方法,并且在第一次出现 not_started
状态时,您可以将 this.started
设置为 true 并基于此将进度更改为锁定。
let myArray = [
{name: "Sam", status: 'completed', progress: 'start'},
{name: "Sara", status: 'not_started', progress: 'start'},
{name: "John", status: 'not_started', progress: 'start'},
{name: "Eric", status: 'not_started', progress: 'start'}
]
const result = myArray.map(function(e) {
if(e.status == 'completed') return {...e, progress: 'completed'}
if (this.started) return { ...e, progress: 'lock'}
if (e.status == 'not_started') this.started = true;
return { ...e};
}, {});
console.log(result)
关于javascript - 如何根据前一个元素更新下一个元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50375732/