简体   繁体   中英

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

Javascript has objects, not associative arrays. 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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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