javascript - 通过对象键将数组项移到前面

标签 javascript arrays

所以我有一个对象数组;

[
    {
        "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/

相关文章:

c++ - char 数组上的奇怪字符到字符串转换

php - 将两个变量传递到 'foreach' 循环中

c - 在 C 中自动将值复制到指针

javascript - 触发 onlick 后定期重复操作

javascript - 如何使 slider 响应(codepen)?

javascript - VueJS v-for 渲染列表,尽管 v-if 评估为 false

java - 将 dataset.addSeries 与 Long[] 值一起使用

java - Java 数组是同构的,而 ArrayList 不是,这是什么意思?

javascript - 使用 jquery toggle 停止点击次数的增加

javascript - 使用中间对齐的 div 防止动画摆动