Mr.Smith
Mr.Smith

Reputation: 190

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?

Upvotes: 0

Views: 64

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

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 = []

Upvotes: 2

Related Questions