所以我有一个对象数组;
[
{
"foo": 2,
"bar": "test"
},
{
"foo": 19,
"bar": "value"
},
{
"foo": 7,
"bar": "temp"
}
]
我需要将具有特定值 foo
的对象移动到数组的开头。值始终在对象中,但不能保证对象一定在数组中。
例如,在运行 moveToFront(19);
之后,我会得到以下内容:
[
{
"foo": 19,
"bar": "value"
},
{
"foo": 2,
"bar": "test"
},
{
"foo": 7,
"bar": "temp"
}
]
我该怎么做?
最佳答案
这应该是相当简单的,你搜索你的数组直到找到你正在寻找的项目然后你拼接
它并且unshift
它回到开头。像这样:
// foo is the target value of foo you are looking for
// arr is your array of items
// NOTE: this is mutating. Your array will be changed (unless the item isn't found)
function promote(foo, arr) {
for (var i=0; i < arr.length; i++) {
if (arr[i].foo === foo) {
var a = arr.splice(i,1); // removes the item
arr.unshift(a[0]); // adds it back to the beginning
break;
}
}
// Matching item wasn't found. Array is unchanged, but you could do something
// else here if you wish (like an error message).
}
如果没有项目具有匹配的 foo
值,那么这对您的数组没有任何作用。如果需要,您可以使用错误消息来处理它。
关于javascript - 通过对象键将数组项移到前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729001/