0

I have a dictionary as as shown below. I am trying to add dict values into them. This is what it stars with

var animals = {
        flying : {},
        underground : {},
        aquatic : {},
        desert : {}
    };

For example: If I wanted to add d = {dove : [<some list>] } into animal[flying], how would i do it? I cannot enter the values manually as thus i am running a loop, I am able to write it manually, but not with program.

I have tried animals[flying] = d, this would work for the first time, but when i try to add another value it would be replaced and not appended.

In the end I am looking for something like this: This is what it ends with

var animals = {
        flying : {
            dove : [<list>],
            sparrow : [<list>],

        },
        underground : {
            rabbits : [<list>],
            squirrel : [Squirrel],

        },
        aquatic : {
            dolphin : [<list>],
            whale : [Squirrel],

        },
        desert : {
            camel : [<list>],
            antelope : [<list>],

        },
    };

3 Answers 3

1

well because

myDict[subcat] = x 

assigns it. You're working with lists. Think about it - when have you ever added an item to a list this way? Of course that overwrites your previous entry. What you want instead is to push the variable into the array (also, this isn't python. Lists are called Arrays and Dictionaries are called Objects. There is a distinction, but that's beyond the scope of an answer here. Google it).

So do this:

myDict = {
    subCat: [],
}

And then when you loop:

myDict[subCat].push(x)
Sign up to request clarification or add additional context in comments.

Comments

1

I think what you want to do is:

animals["flying"] = Object.assign(animals["flying"], d);

E.g.

animals = {
    flying: {}
}

d = { dove: [1, 2, 3] }
Object.assign(animals["flying"], d);
d = { sparrow: [1, 2, 3] }
Object.assign(animals["flying"], d);
console.log(animals); //{"flying":{"dove":[1,2,3],"sparrow":[1,2,3]}}

1 Comment

That’s equivalent to Object.assign(animals["flying"], d);. Object.assign already mutates the first argument. Also animals["flying"] can be rewritten as animals.flying.
0
var newAnimal = {name: 'bird'};    
if(animals['flying']['dove'] && animals['flying']['dove'].length > 0) {
   //List already exists so add the new animal
   //TODO also check if the animal is already in the list?
   animals['flying']['dove'].push(newAnimal);
}else {
   //Create the new list
   animals['flying']['dove'] = [newAnimal];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.