所以我有一个对象数组;
[
{
"foo": 2,
"bar": "test"
},
{
"foo": 19,
"bar": "value"
},
{
"foo": 7,
"bar": "temp"
}
]
Run Code Online (Sandbox Code Playgroud)
我需要将具有特定值的对象移动foo
到数组的开头.值始终在对象中,但不保证对象将在数组中.
所以在运行之后moveToFront(19);
,我有以下内容:
[
{
"foo": 19,
"bar": "value"
},
{
"foo": 2,
"bar": "test"
},
{
"foo": 7,
"bar": "temp"
}
]
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
这应该是相当简单的,你搜索你的数组,直到你找到你正在寻找的项目,然后你splice
出来,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).
}
Run Code Online (Sandbox Code Playgroud)
如果没有匹配foo
值的项,那么这对您的数组不起作用.如果需要,您可以使用错误消息处理它.
var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}]
// move {foo:7} to the front
data.some(item => item.foo == 7 && data.unshift(item))
// print result
console.log(data)
Run Code Online (Sandbox Code Playgroud)
var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}]
// move {foo:7} to the front
const clonedData = [...data]
clonedData.some((item, i, arr) => item.foo == 7 && arr.unshift(item))
// print result
console.log(clonedData)
Run Code Online (Sandbox Code Playgroud)
var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}]
// find the index of the target array item:
var itemIndex = data.findIndex(item => item.foo == 7);
data.splice(
0, // new index,
0, // no removal
data.splice(itemIndex, 1)[0] // detach the item and return it
);
// print result
console.log(data)
Run Code Online (Sandbox Code Playgroud)
如果您使用lodash并且需要支持旧版浏览器,请使用以下
some()
方法:
findIndex()
这将使用键将Array Object移动到数组_.findIndex
的开头.