我正试图从一个看起来像这样的对象中获取
[{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}]
到此:
[{current: [], queue: [3]}, {current: [], queue: [1]}, {current: [], queue: [2]}]
基本上,我想将“当前”中的项目推送到下一个项目的队列。
我想使用lodash或ramda.js在功能样式中执行此操作。我对功能样式编程很陌生,我遇到了如何做到这一点,特别是处理arr [2] - > arr [0]案例。我想过使用reduce,但我不确定这是否是解决问题的最佳方法。
答案 0 :(得分:0)
您可以使用lodash#map
来实现此目标。
var result = array.map(function(value, index) {
// get previous array value
var prev = array[(index - 1 + array.length) % array.length];
return Object.assign(
{}, // Makes sure that we don't mutate the original array
value, // retain properties that are not `current` and `queue`
{ current: prev.queue, queue: prev.current } // override
);
});
var array = [{
current: [1],
queue: []
}, {
current: [2],
queue: []
}, {
current: [3],
queue: []
}];
var result = array.map(function(value, index) {
// get previous array value
var prev = array[(index - 1 + array.length) % array.length];
return Object.assign(
{}, // Makes sure that we don't mutate the original array
value, // retain properties that are not `current` and `queue`
{ current: prev.queue, queue: prev.current } // override
);
});
console.log(result);

.as-console-wrapper { min-height: 100%; top: 0; }

答案 1 :(得分:0)
一个有趣的ramda解决方案:
[1, 2, 3]
到[3, 1, 2, 3]
)aperture
创建对(例如:[[3,1], [1,2], [2,3]]
)[4, 3, 5]
) mergePair
和loop
函数的编写方式可能不同......我无法在文档中找到合适的候选函数。
const data = [{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}];
const mergePair = ([left, right]) =>
({ current: [], queue: concat(right.queue, left.current) })
const loop = arr => prepend(last(arr), arr);
const updateQueue = pipe(
loop,
aperture(2),
map(mergePair)
)
updateQueue(data);
尝试 here
答案 2 :(得分:-1)
一种简单的方法是进行深层复制并将最后一项移动到该副本中的第一个位置。
然后迭代原始内容以将每个队列更新为重新排列的副本中的匹配索引
var data = [{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}],
// make a copy of array
copy = JSON.parse(JSON.stringify(data));
// move last to first in copy
copy.unshift(copy.pop());
data.forEach((el,i)=> {
el.queue = copy[i].current;
el.current.length = 0;
});
console.log(data)