javascript - 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.
解决方案
映射数组,并使用模运算从循环中的前一项中获取任务。
与%
运算符不同,使用负数取模的结果将是正余数。这是必需的,因为在第一项 ( i
is 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)
推荐阅读
- batch-file - 如何在不关闭 cmd 窗口的情况下使该脚本在 30 分钟后重复该命令?
- excel - Excel vba for循环
- apache-spark - 如果我们在 case when 语句中使用 udf,火花会如何表现,它是否将 udf 应用于所有记录,然后应用 case 过滤器?
- c# - 使用表达式函数返回值
- xamarin - 如何在 Xamarin Forms 中使用嵌入资源字体文件中的图标
- javascript - Javascript / CSS 砌体 - 尊重列
- mysql - 如何将查询集限制为 MySQL 中的 ID 子集?
- apache-storm - Apache Storm 2.1.0 内存相关配置
- django - Django MaterializeCSS - 工作,但不确定设置 css 和 js 的正确方法?
- r - 在堆积条形图中自定义不同大小的标签(ggplot2)