所以我有一个对象数组;
[ { "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" } ]
我该怎么做呢?
这应该是相当简单的,你搜索你的数组,直到你找到你正在寻找的项目,然后你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). }
如果没有匹配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)