带下划线的重新排序集合

发布于 2024-12-18 20:09:13 字数 277 浏览 3 评论 0原文

我是新来强调所以请原谅我的无知。

有没有一种快速简便的方法可以执行以下操作:

men:{gerald:{"name":"Gerald", "age":50},mike:{"name":"Mike", "age":50},charles:{"name":"Charles", "age":50}}

其中名称是 Mike - 设置在位置 1(索引 0)

我只想随机排列项目,以便第一个项目由我选择的名称设置。

非常欢迎任何帮助。

I'm new to underscore so pardon my ignorance.

Is there a quick and easy way to do the following:

men:{gerald:{"name":"Gerald", "age":50},mike:{"name":"Mike", "age":50},charles:{"name":"Charles", "age":50}}

Where name is Mike - set at position 1 (index 0)

I just want to shuffle the items so the first item is set by the name I choose.

Any help more than welcome.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许久 2024-12-25 20:09:13

由于 _.suffle 会打乱所有元素,因此您需要拼接除预定义元素之外的所有元素,对它们进行打乱,并将打乱后的元素连接到包含预定义元素的现有数组。

类似于:

var orig = [1, 2, 3, 4, 5],
    shuffled = [];

shuffled[0] = orig[2]; // 3 is the predefined element

shuffled = shuffled.concat( _.shuffle( orig.slice(0,2).concat( orig.slice(3) ) ) );

它获取没有预定义元素的数组,对其进行洗牌,并将其连接到 shuffled 数组,该数组包含预定义变量作为其第一个元素。

Since _.suffle shuffles all elements, you'd need to splice out all elements but the predefined one, shuffle them, and concatenate the shuffled elements to an existing array which contains the predefined element.

Something like:

var orig = [1, 2, 3, 4, 5],
    shuffled = [];

shuffled[0] = orig[2]; // 3 is the predefined element

shuffled = shuffled.concat( _.shuffle( orig.slice(0,2).concat( orig.slice(3) ) ) );

which gets the array without the predefined element, shuffles it, and concatenates it to the shuffled array, which contains the predefined variable as its first element.

国际总奸 2024-12-25 20:09:13

您不需要 underscore.js。 Array.sort 会做得很好:

myJson.men.sort(function(a, b) { return b.name == "Mike" })

这并不是真正的排序模型用法,但它可以完成工作。


此外,您的 JSON 无效。您需要在数组周围使用方括号,而不是花括号:

{
    "men": [{
        "name": "Gerald", "age": 50
    },{
        "name": "Mike", "age": 50
    },{
        "name": "Charles", "age": 50
    }]
}


编辑:

您无法“排序”该 JSON。您要求做的是订购一个关联数组。这没有任何意义。如果项目的顺序很重要,那么您需要一个数组,而不是一个对象。

You don't need underscore.js. Array.sort will do fine:

myJson.men.sort(function(a, b) { return b.name == "Mike" })

This isn't really model usage of sort, but it does the job.


Also, your JSON is invalid. You need square brackets around the array, not curlies:

{
    "men": [{
        "name": "Gerald", "age": 50
    },{
        "name": "Mike", "age": 50
    },{
        "name": "Charles", "age": 50
    }]
}


Edit:

You can't "order" that JSON. What you're asking to do is order an associative array. This doesn't make any sense. If order of items is important, you want an array, not an object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文