简体   繁体   English

如何从字符串创建关联数组?

[英]How can I create an associative array from a string?

This is what I have:这就是我所拥有的:

<input type="checkbox" name="selectedId[{{ order.id }}]">

const orders = [];
$("input[type=checkbox][name*='selectedId']:checked").each(function (index) {
    let id          = $(this).attr('name').match(/[-0-9]+/);
    orders[index]   = id[0];
});

And I get:我得到:

orders = [0 => 1, 1 => 2]

What I would like to get is:我想得到的是:

orders = [
    0 => ["id" => 1],
    1 => ["id" => 2]
];

orders[index]["id"] = id[0] doesn't work订单[索引]["id"] = id[0] 不起作用

Javascript has objects, not associative arrays. Javascript 有对象,而不是关联数组。 For your desired result, you'd want something like this:对于您想要的结果,您需要这样的东西:

let orders = [];
$("input[type=checkbox][name*='selectedId']:checked").each(function (index) {
    orders[index] = { id: $(this).attr('name').match(/[-0-9]+/)[0] };
});

or you could also use Array.push()或者你也可以使用Array.push()

orders.push({ id: $(this).attr('name').match(/[-0-9]+/)[0] });

Also, const is meant for non-mutable constants, so you may want to use let instead.此外, const用于非可变常量,因此您可能想改用let

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM