简体   繁体   中英

Javascript Push array to array with unique key

I have object with array like that:

const result = {
    key1: [],
    key2: [],
    key3: [],
    key4: []
};

And I want to push to one of the "key" something like that:

result.key1.push({key11: []})
result.key1.push({key12: []})
result.key1.push({key13: []})

But I need the result looks like that:

{
    key1: [
        key11: [],
        key12: [],
        key13: []
    ],
    key2: [],
    key3: [],
    key4: []
}

I tried almost everything did I miss something?

You're mixing up objects and arrays. Arrays have items in order, from 0 to length - 1, while objects have named keys. It seems that you're looking for having named keys, so you need to create an object instead.

const result = {
    key1: {},
    key2: {},
    key3: {},
    key4: {},
};

Now simply assign items.

result.key1.key11 = []
result.key1.key12 = []
result.key1.key13 = []

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