首页 > 解决方案 > How do i move through the values of keys in javascript?

问题描述

How would i cycle move the key values in a js array,

for example:
    {Name:"A", Task:"Task1"},
    {Name:"B", Task:"Task2"},
    {Name:"C", Task:"Task3"},

to
    {Name:"A", Task:"Task3"},
    {Name:"B", Task:"Task1"},
    {Name:"C", Task:"Task2"},

to clarify further it should be a function that every time is run "shifts the task column" by one.

I have tried using methods such as:

ary.push(ary.shift()); 

however i don't know any way that i can specifically apply this to a specific key while not moving the others.

标签: javascriptarrays

解决方案


映射数组,并使用模运算从循环中的前一项中获取任务。

%运算符不同,使用负数取模的结果将是正余数。这是必需的,因为在第一项 ( iis 0)i - 1中将是-1.

const modulo = (a, n) => ((a % n ) + n) % n

const fn = arr =>
  arr.map((o, i) => ({
    ...o,
    Task: arr[modulo((i - 1), arr.length)].Task
  }))

const arr = [{"Name":"A","Task":"Task1"},{"Name":"B","Task":"Task2"},{"Name":"C","Task":"Task3"}]

const result = fn(arr)

console.log(result)


推荐阅读