2

I have an object that looks like this:

{
 object1: {
            version: 1.0.0,
            name: Name1
          },
 object2: {
            version: 1.0.0,
            name: Name2
          },
 object3: {
            version: 1.0.0,
            name: Name3
          }
}

I need to make an array with each objects name. How can i loop over this object and get each objects name?

4 Answers 4

2

with the for... in loop:

let obj = {
       object1: {
            version: "1.0.0",
            name: "Name1"
          },
       object2: {
            version: "1.0.0",
            name: "Name2"
          },
       object3: {
            version: "1.0.0",
            name: "Name3"
          }
    }

    for(let key in obj){
       name = obj[key].name;
       console.log(name);
    }

Sign up to request clarification or add additional context in comments.

Comments

1

https://github.com/airbnb/javascript#iterators-and-generators

Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of. eslint: no-iterator no-restricted-syntax

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

Use ... Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.

So:

const names1 = Object.values(obj).map((sub_obj) => sub_obj.name)
const names2 = Object.keys(obj).map((key) => obj[key].name)

Comments

0

If you don't need IE support there is a functional approach: Object.entries()

const obj = {
 object1: {
            version: 1.0.0,
            name: Name1
          },
 object2: {
            version: 1.0.0,
            name: Name2
          },
 object3: {
            version: 1.0.0,
            name: Name3
          }
}

const names = Object.entries(obj).map(([key, value]) => value.name)

Comments

0

i hope this works...

             let obj = {
                object1: {
                            version: "1.0.0",
                            name: "Name1"
                        },
                object2: {
                            version: "1.0.0",
                            name: "Name2"
                        },
                object3: {
                            version: "1.0.0",
                            name: "Name3"
                        }
                };


            let array = Object.values(obj); //push values to new array without keys                
            let Names = []; //Empty Names array... 

            array.map(o => {
                Names.push(o.name);  //loop and push the names to new array
            });

            console.log(Names); //array of names;

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.